如何使用JavaScript获取私有IP?

时间:2017-03-22 02:12:25

标签: javascript webrtc

我正在使用我在Github上找到的代码,使用WebRTC获取专用网络的IP地址。

这在Chrome中完美运行,但在Firefox中,我只在响应中获得公共IP地址。

有解决方法吗?我只针对这些浏览器的最新版本。



            function getIPs(callback){
                var ip_dups = {};

                var RTCPeerConnection = window.RTCPeerConnection
                    || window.mozRTCPeerConnection
                    || window.webkitRTCPeerConnection;

                //bypass naive webrtc blocking using an iframe
                if(!RTCPeerConnection){
                    var win = iframe.contentWindow;
                    RTCPeerConnection = win.RTCPeerConnection
                        || win.mozRTCPeerConnection
                        || win.webkitRTCPeerConnection;
                }

                //minimal requirements for data connection
                var mediaConstraints = {
                    optional: [{RtpDataChannels: true}]
                };

                var servers = {iceServers: [{urls: "stun:stun.l.google.com:19302"}]};

                //construct a new RTCPeerConnection
                var pc = new RTCPeerConnection(servers, mediaConstraints);

                function handleCandidate(candidate){
                    //match just the IP address
                    var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
                    var ip_addr = ip_regex.exec(candidate)[1];

                    //remove duplicates
                    if(ip_dups[ip_addr] === undefined)
                        callback(ip_addr);

                    ip_dups[ip_addr] = true;
                }

                pc.onicecandidate = function(ice){
                    if(ice.candidate)
                        handleCandidate(ice.candidate.candidate);
                };

                pc.createDataChannel("");

                pc.createOffer(function(result){
                    pc.setLocalDescription(result, function(){}, function(){});
                }, function(){});

                //wait for a while to let everything done
                setTimeout(function(){
                    //read candidate info from local description
                    var lines = pc.localDescription.sdp.split('\n');

                    lines.forEach(function(line){
                        if(line.indexOf('a=candidate:') === 0)
                            handleCandidate(line);
                    });
                }, 1000);
            }

            // Get IP
            getIPs(function(ip){
                if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)){
                    console.log('Private ip :' + ip)
                }else {
                    console.log('Public ip :' + ip)
                }
            });

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
    </body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

最好的办法是通过php

&#13;
&#13;
<?php $ip =  $_SERVER['REMOTE_ADDR']; ?>

<!-- if you want to show the ip just -->

<?php echo $ip; ?>
&#13;
&#13;
&#13;

但是如果你需要通过javascript获取ip,你将需要一个api:

www.freegeoip.net

    $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
      console.log(JSON.stringify(data, null, 2));

});

这将导致json文件

{
  "ip": "116.12.250.1",
  "country_code": "SG",
  "country_name": "Singapore",
  "region_code": "01",
  "region_name": "Central Singapore Community Development Council",
  "city": "Singapore",
  "zip_code": "",
  "time_zone": "Asia/Singapore",
  "latitude": 1.2931,
  "longitude": 103.8558,
  "metro_code": 0
}

如果要在html中显示json元素,则需要

来自mafintosh示例的https://github.com/mafintosh/json-markup也是

const jsonMarkup = require('json-markup')
const html = jsonMarkup({hello:'world'})
document.querySelector('#myElem').innerHTML = html
HTML

<link ref="stylesheet" href="style.css">
<div id="myElem></div>