JavaScript 如何获取本机IP地址
warning:
这篇文章距离上次修改已过205天,其中的内容可能已经有所变动。
在JavaScript中获取用户的本机IP地址通常需要使用Web API或者后端服务,因为出于安全考虑,客户端的文件系统、网络配置等信息是受限制的。以下是一个使用WebRTC API获取本机IP地址的例子:
function getLocalIP() {
return new Promise((resolve, reject) => {
let RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection;
if (RTCPeerConnection) {
let rtc = new RTCPeerConnection({iceServers: []});
rtc.createDataChannel('', {reliable: false});
rtc.onicecandidate = (evt) => {
if (evt.candidate) {
let ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
let ip_addr = ip_regex.exec(evt.candidate.candidate)[1];
resolve(ip_addr);
rtc.onicecandidate = null;
}
};
rtc.createOffer((offerDesc) => {
rtc.setLocalDescription(offerDesc);
}, (e) => reject(e));
} else {
reject(new Error('RTCPeerConnection not supported'));
}
});
}
getLocalIP().then(ip => console.log(ip)).catch(e => console.error(e));
这段代码创建了一个RTCPeerConnection对象,并试图建立一个连接。在这个过程中,通过onicecandidate
事件回调函数,可以获取到本地的IP地址。
请注意,这个方法可能不会在所有的浏览器中工作,因为某些浏览器可能不允许在不安全的上下文中使用MediaStream API。此外,某些网络环境下可能获取不到正确的IP地址。
评论已关闭