-
Notifications
You must be signed in to change notification settings - Fork 27
如何使用JavaScript获取IP地址 #18
Copy link
Copy link
Open
Labels
Description

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 🥇
Reactions are currently unavailable