如何使用JavaScript获取IP地址

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

使用 webRTC (获取私有IP)

RTCPeerConnection技术详细可见MDN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 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链接

    1
    2
    3
    $.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形式在页面上。

1
2
3
4
5
6
<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 🥇