在JavaScript中获取手机上的IP地址可以通过几种不同的方法实现,但需要注意的是,由于安全和隐私的原因,浏览器环境下的JavaScript并没有直接提供获取本地IP地址的标准API。以下是几种常见的方法:
WebRTC(Web Real-Time Communication)允许网页浏览器进行实时语音对话或视频对话。在建立连接的过程中,WebRTC可以获取到本地IP地址。
function getLocalIPs(callback) {
var ips = [];
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({ iceServers: [] });
pc.createDataChannel('');
pc.onicecandidate = function(e) {
if (!e.candidate) {
pc.close();
callback(ips);
return;
}
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
if (ips.indexOf(ip) == -1) {
ips.push(ip);
}
};
pc.createOffer().then(function(sdp) {
pc.setLocalDescription(sdp);
}).catch(function(e) {
console.error(e);
});
}
getLocalIPs(function(ips) {
console.log('Your IP addresses are: ', ips);
});
另一种方法是使用第三方服务,这些服务通常通过AJAX请求返回客户端的公网IP地址。
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => console.log('Your public IP address is:', data.ip));
通过上述方法,可以在JavaScript中获取手机的IP地址,但务必注意保护用户隐私和安全。
领取专属 10元无门槛券
手把手带您无忧上云