Luk*_*uge 16 networking google-chrome google-chrome-extension
我正在开发一个chrome扩展,它应该发现然后与本地网络中的其他设备通信.要发现它们,需要找出自己的IP地址,找出网络的IP范围,以检查其他设备.我被困在如何找到本地机器的IP地址(我不是在谈论本地主机,我也不是在谈论暴露在互联网上的地址,而是在本地网络上的地址).基本上,我喜欢的是在background.js中的终端中获取ifconfig输出.
Chrome Apps API提供chrome.socket似乎可以执行此操作,但是,它不适用于扩展程序.通过API读取扩展我没有找到任何似乎使我能够找到本地IP的东西.
我错过了什么或者由于某种原因这是不可能的吗?是否有任何其他的方式来发现网络上的其他设备,这也将做得很好(因为它们是在同一个IP范围),但同时也有一些传言从2012年的十二月,有可能是用于扩展发现API似乎没有任何东西存在.
有人有什么想法吗?
Rob*_*b W 35
您可以通过WebRTC API获取本地IP地址列表(更准确地说:本地网络接口的IP地址).任何Web应用程序(不仅仅是Chrome扩展程序)都可以使用此API.
例:
// Example (using the function below).
getLocalIPs(function(ips) { // <!-- ips is an array of local IP addresses.
document.body.textContent = 'Local IP addresses:\n ' + ips.join('\n ');
});
function getLocalIPs(callback) {
var ips = [];
var RTCPeerConnection = window.RTCPeerConnection ||
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
var pc = new RTCPeerConnection({
// Don't specify any stun/turn servers, otherwise you will
// also find your public IP addresses.
iceServers: []
});
// Add a media line, this is needed to activate candidate gathering.
pc.createDataChannel('');
// onicecandidate is triggered whenever a candidate has been found.
pc.onicecandidate = function(e) {
if (!e.candidate) { // Candidate gathering completed.
pc.close();
callback(ips);
return;
}
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
if (ips.indexOf(ip) == -1) // avoid duplicate entries (tcp/udp)
ips.push(ip);
};
pc.createOffer(function(sdp) {
pc.setLocalDescription(sdp);
}, function onerror() {});
}Run Code Online (Sandbox Code Playgroud)
<body style="white-space:pre"> IP addresses will be printed here... </body>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13591 次 |
| 最近记录: |