javascript - 使用带有 chrome 的 Javascript 获取本地 IP 返回哈希/主机名
问题描述
我正在使用此代码https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only允许在浏览器中获取本地 IP(Chrome在我的情况下)使用ice.candidate,但在某些情况下它不会返回IP,而是返回一种主机名(例如“0ddcdf5f-6ba6-47fb-8183-e44f51a1afc7.local”)。我还没有找到真正的原因,因为有时它不起作用。
我也没有找到替代方案。
这是一个测试https://jsfiddle.net/42g5jzpx/,在我的计算机上运行良好,但在其他计算机上运行良好,返回上面的主机名。
/**
* 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);
});
谢谢
保罗
解决方案
推荐阅读
- reactjs - 如何使用 react-jss 组件为子元素添加样式?
- angularjs - AngularJS 为工厂/服务附加价值
- sql - 如何在sql server中获取本周的每日数据
- artificial-intelligence - 我应该用什么来检测人群中的特定人?
- spring-boot - 基本 SpringBoot App 无法在 STS 中构建
- arduino - Arduino/Attiny85:ISR 和端口操作延迟
- python-3.x - symbolicRegressor 的 Y_train 值
- c# - 在验证循环中递增 errorProvider
- powershell - 从 powershell Get-ChildItem 结果中排除文件
- c# - 从列表列表中的组合框项目中显示列表