Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

后端 未结 16 1462
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 11:45

I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client\'s computer. Is that possible?

相关标签:
16条回答
  • 2020-11-22 12:05

    Edit: This question gave me an itch, so I put up a JSONP webservice on Google App Engine that returns the clients ip address. Usage:

    <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>
    

    Yay, no server proxies needed.


    Pure JS can't. If you have a server script under the same domain that prints it out you could send a XMLHttpRequest to read it.

    0 讨论(0)
  • 2020-11-22 12:07

    The hosted JSONP version works like a charm, but it seems it goes over its resources during night time most days (Eastern Time), so I had to create my own version.

    This is how I accomplished it with PHP:

    <?php
    header('content-type: application/json; charset=utf-8');
    
    $data = json_encode($_SERVER['REMOTE_ADDR']);
    echo $_GET['callback'] . '(' . $data . ');';
    ?>
    

    Then the Javascript is exactly the same as before, just not an array:

    <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>
    

    Simple as that!

    Side note: Be sure to clean your $_GET if you're using this in any public-facing environment!

    0 讨论(0)
  • 2020-11-22 12:07

    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. :-)

    0 讨论(0)
  • 2020-11-22 12:08

    Very late, but I guess many people will still land here through "Google Airlines". A moderm approach is to use WebRTC that doesn't require server support.

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

    Next code is a copy&paste from 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.";
    }   
    
    0 讨论(0)
提交回复
热议问题