使用 webRTC (获取私有IP)
/**
* 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>
在 vue 中,可以这样做:
// 封装
getUserIp () {
let url = 'https://api.ipify.org?format=json'
return axios.get(url).then(res => res.data.ip)
}
// 获取
async funX () {
let ip = await this.getUserIp()
console.log(ip) // 获取用户公网 ip 地址
},