programing

클라이언트 측 Javascript를 사용하여 DNS 조회 (호스트 이름에서 IP 주소로)를 수행 할 수 있습니까?

nasanasas 2020. 10. 5. 08:02
반응형

클라이언트 측 Javascript를 사용하여 DNS 조회 (호스트 이름에서 IP 주소로)를 수행 할 수 있습니까?


클라이언트 컴퓨터에서 볼 수있는 DNS 조회 (호스트 이름에서 IP 주소로)를 수행하기 위해 클라이언트 측 자바 스크립트를 사용하고 싶습니다. 가능합니까?


자바 스크립트 표준 라이브러리에는 호스트 나 IP 주소에 대한 개념이 없습니다. 따라서 호스트 이름을 찾으려면 일부 외부 서비스에 액세스해야합니다.

호스트 이름의 IP 주소를 조회하고 javascript를 통해 액세스하는 cgi-bin을 호스팅하는 것이 좋습니다.


편집 :이 질문은 나에게 가려움을 주었으므로 클라이언트 IP 주소를 반환하는 Google App Engine에 JSONP 웹 서비스를 올렸습니다. 용법:

<script type="application/javascript">
function getip(json){
  alert(json.ip); // alerts the ip address
}
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"> </script>

예, 서버 프록시가 필요하지 않습니다.


Pure JS는 할 수 없습니다. 인쇄하는 동일한 도메인에 서버 스크립트가있는 경우 XMLHttpRequest를 보내서 읽을 수 있습니다.


아주 늦었지만 여전히 많은 사람들이 "Google Airlines"를 통해 여기에 착륙 할 것 같습니다. Moderm 접근 방식은 서버 지원이 필요하지 않은 WebRTC를 사용하는 것입니다.

https://hacking.ventures/local-ip-discovery-with-html5-webrtc-security-and-privacy-risk/

다음 코드는 http://net.ipcalf.com/ 에서 복사 및 붙여 넣기입니다.

// NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

if (RTCPeerConnection) (function () {
    var rtc = new RTCPeerConnection({iceServers:[]});
    if (window.mozRTCPeerConnection) {      // FF needs a channel/stream to proceed
        rtc.createDataChannel('', {reliable:false});
    };  

    rtc.onicecandidate = function (evt) {
        if (evt.candidate) grepSDP(evt.candidate.candidate);
    };  
    rtc.createOffer(function (offerDesc) {
        grepSDP(offerDesc.sdp);
        rtc.setLocalDescription(offerDesc);
    }, function (e) { console.warn("offer failed", e); }); 


    var addrs = Object.create(null);
    addrs["0.0.0.0"] = false;
    function updateDisplay(newAddr) {
        if (newAddr in addrs) return;
        else addrs[newAddr] = true;
        var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; }); 
        document.getElementById('list').textContent = displayAddrs.join(" or perhaps ") || "n/a";
    }   

    function grepSDP(sdp) {
        var hosts = []; 
        sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
            if (~line.indexOf("a=candidate")) {     // http://tools.ietf.org/html/rfc4566#section-5.13
                var parts = line.split(' '),        // http://tools.ietf.org/html/rfc5245#section-15.1
                    addr = parts[4],
                    type = parts[7];
                if (type === 'host') updateDisplay(addr);
            } else if (~line.indexOf("c=")) {       // http://tools.ietf.org/html/rfc4566#section-5.7
                var parts = line.split(' '), 
                    addr = parts[2];
                updateDisplay(addr);
            }   
        }); 
    }   
})(); else {
    document.getElementById('list').innerHTML = "<code>ifconfig | grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
    document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}   

호스팅 된 JSONP 버전은 매력처럼 작동하지만 대부분의 날 (동부 표준시) 밤 시간에 리소스를 넘기는 것 같아서 나만의 버전을 만들어야했습니다.

이것이 내가 PHP로 그것을 달성 한 방법입니다.

<?php
header('content-type: application/json; charset=utf-8');

$data = json_encode($_SERVER['REMOTE_ADDR']);
echo $_GET['callback'] . '(' . $data . ');';
?>

그런 다음 Javascript는 배열이 아니라 이전과 똑같습니다.

<script type="application/javascript">
function getip(ip){
    alert('IP Address: ' + ip);
}
</script>

<script type="application/javascript" src="http://www.anotherdomain.com/file.php?callback=getip"> </script>

그렇게 간단합니다!

참고 : 공공 환경에서 사용하는 경우 $ _GET을 반드시 청소하십시오!


나는 이것이 오래된 질문이라는 것을 알고 있지만 내 솔루션이 다른 사람들에게 도움이 될 수 있습니다.

I find that the JSON(P) services which make this easy do not last forever but the following JavaScript works well for me at the time of writing.

<script type="text/javascript">function z (x){ document.getElementById('y').innerHTML=x.query }</script>
<script type='text/javascript' src='http://ip-api.com/json/zero.eu.org?callback=z'></script>

The above writes my server's IP on the page it is located but the script can be modified to find any IP by changing 'zero.eu.org' to another domain name. This can be seen in action on my page at: http://meon.zero.eu.org/


There's a third-party service which provides a CORS-friendly REST API to perform DNS lookups from the browser - https://exana.io/tools/dns/


As many people said you need to use an external service and call it. And that will only get you the DNS resolution from the server perspective.

If that's good enough and if you just need DNS resolution you can use the following Docker container:

https://github.com/kuralabs/docker-webaiodns

Endpoints:

[GET] /ipv6/[domain]: Perform a DNS resolution for given domain and return the associated IPv6 addresses.

 {
     "addresses": [
         "2a01:91ff::f03c:7e01:51bd:fe1f"
     ]
 }

[GET] /ipv4/[domain]: Perform a DNS resolution for given domain and return the associated IPv4 addresses.

 {
     "addresses": [
         "139.180.232.162"
     ]
 }

My recommendation is that you setup your web server to reverse proxy to the container on a particular endpoint in your server serving your Javascript and call it using your standard Javascript Ajax functions.


Doing this would require to break the browser sandbox. Try to let your server do the lookup and request that from the client side via XmlHttp.


sure you can do that without using any addition, just pure javascript, by using this method of dns browser.dns.resolve("example.com"); but it is compatible just with FIREFOX 60 you can see more information on MDN https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns/resolve


There is a javascript library DNS-JS.com that does just this.

DNS.Query("dns-js.com",
    DNS.QueryType.A,
    function(data) {
        console.log(data);
});

I don't think this is allowed by most browsers for security reasons, in a pure JavaScript context as the question asks.


Firefox has a built-in API for this since v60, for WebExtensions:

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns/resolve


Maybe I missed the point but in reply to NAVY guy here is how the browser can tell you the 'requestor's' IP address (albeit maybe only their service provider).

Place a script tag in the page to be rendered by the client that calls (has src pointing to) another server that is not loaded balanced (I realize that this means you need access to a 2nd server but hosting is cheap these days and you can set this up easily and cheaply).

This is the kind of code that needs to be added to client page:

On the other server "someServerIown" you need to have the ASP, ASPX or PHP page that;

----- contains server code like this:

"<% Response.Write("var clientipaddress = '" & Request.ServerVariables("REMOTE_ADDR") & "';") %>" (without the outside dbl quotes :-))

---- and writes this code back to script tag:

   var clientipaddress = '178.32.21.45';

This effectively creates a Javascript variable that you can access with Javascript on the page no less.

Hopefully, you access this var and write the value to a form control ready for sending back.

When the user posts or gets on the next request your Javascript and/or form sends the value of the variable that the "otherServerIown" has filled in for you, back to the server you would like it on.

This is how I get around the dumb load balancer we have that masks the client IP address and makes it appear as that of the Load balancer .... dumb ... dumb dumb dumb!

I haven't given the exact solution because everyone's situation is a little different. The concept is sound, however. Also, note if you are doing this on an HTTPS page your "otherServerIOwn" must also deliver in that secure form otherwise Client is alerted to mixed content. And if you do have https then make sure ALL your certs are valid otherwise client also gets a warning.

Hope it helps someone! Sorry, it took a year to answer/contribute. :-)


My version is like this:

php on my server:

<?php
    header('content-type: application/json; charset=utf-8');

    $data = json_encode($_SERVER['REMOTE_ADDR']);


    $callback = filter_input(INPUT_GET, 
                 'callback',
                 FILTER_SANITIZE_STRING, 
                 FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
    echo $callback . '(' . $data . ');';
?>

jQuery on the page:

var self = this;
$.ajax({
    url: this.url + "getip.php",
    data: null,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp'

}).done( function( json ) {

    self.ip = json;

});

It works cross domain. It could use a status check. Working on that.


If the client has Java installed, you could do something like this:

ipAddress = java.net.InetAddress.getLocalHost().getHostAddress();

Other than that, you will probably have to use a server side script.

참고URL : https://stackoverflow.com/questions/102605/can-i-perform-a-dns-lookup-hostname-to-ip-address-using-client-side-javascript

반응형