Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何使用JavaScript获取IP地址 #18

Open
gnipbao opened this issue Nov 21, 2017 · 0 comments
Open

如何使用JavaScript获取IP地址 #18

gnipbao opened this issue Nov 21, 2017 · 0 comments

Comments

@gnipbao
Copy link
Owner

gnipbao commented Nov 21, 2017

articleocw-57dfeb2a430a6
JavaScript是无法获得或存储在客户端的IP。但是由于JavaScript能够发送HTTP请求,而服务器端语言能够获取用户的公网IP,所以你可以利用这个获取IP。 换句话说,如果你想得到一个用户就取决于请求任何服务器检索公网IP。 随着WebRTC技术的发展,利用rtcpeerconnection可以检索用户私有IP。

使用 webRTC (获取私有IP)

RTCPeerConnection技术详细可见MDN

/**
 * Get the user IP throught the webkitRTCPeerConnection
 * @param onNewIP {Function} listener function to expose the IP locally
 * @return undefined
 */
function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
    //compatibility for firefox and chrome
    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    var pc = new myPeerConnection({
        iceServers: []
    }),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

    function iterateIP(ip) {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
    }

     //create a bogus data channel
    pc.createDataChannel("");

    // create offer and set local description
    pc.createOffer().then(function(sdp) {
        sdp.sdp.split('\n').forEach(function(line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(iterateIP);
        });
        
        pc.setLocalDescription(sdp, noop, noop);
    }).catch(function(reason) {
        // An error occurred, so handle the failure to connect
    });

    //listen for candidate events
    pc.onicecandidate = function(ice) {
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
    };
}

// Usage

getUserIP(function(ip){
    alert("Got IP! :" + ip);
});

使用第三方服务(获取公网IP)

  • 不安全的http链接
$.getJSON('http://ipinfo.io', function(data){
    console.log(data);
});
  • 安全的https链接(推荐)
API URI Response Type Sample Output (IPv4) Sample Output (IPv6)
https://api.ipify.org text 11.111.111.111
https://api.ipify.org?format=json json {"ip":"11.111.111.111"}
https://api.ipify.org?format=jsonp jsonp callback({"ip":"11.111.111.111"})
https://api.ipify.org?format=jsonp&callback=getip jsonp getip({"ip":"11.111.111.111"});

可以使用jsonp形式在页面上。

<script type="application/javascript">
  function getIP(json) {
    document.write("My public IP address is: ", json.ip);
  }
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

Have fun 🥇

@gnipbao gnipbao changed the title 使用JavaScript获取IP地址 如何使用JavaScript获取IP地址 Nov 21, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant