搜索
查看: 899|回复: 0

Get local and public IP addresses in JavaScript

[复制链接]

1839

主题

2255

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
11913
发表于 2015-2-6 00:46:21 | 显示全部楼层 |阅读模式
from:https://github.com/diafygi/webrtc-ips


Firefox 跟 Chrome支持WebRTC可以向STUN服务器请求,返回内外网IP,不同于XMLHttpRequest请求,STUN请求开发者工具当中看不到网络请求的。
  1. //get the IP addresses associated with an account
  2. function getIPs(callback){
  3.     var ip_dups = {};

  4.     //compatibility for firefox and chrome
  5.     var RTCPeerConnection = window.RTCPeerConnection
  6.         || window.mozRTCPeerConnection
  7.         || window.webkitRTCPeerConnection;
  8.     var mediaConstraints = {
  9.         optional: [{RtpDataChannels: true}]
  10.     };

  11.     //firefox already has a default stun server in about:config
  12.     //    media.peerconnection.default_iceservers =
  13.     //    [{"url": "stun:stun.services.mozilla.com"}]
  14.     var servers = undefined;

  15.     //add same stun server for chrome
  16.     if(window.webkitRTCPeerConnection)
  17.         servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

  18.     //construct a new RTCPeerConnection
  19.     var pc = new RTCPeerConnection(servers, mediaConstraints);

  20.     //listen for candidate events
  21.     pc.onicecandidate = function(ice){

  22.         //skip non-candidate events
  23.         if(ice.candidate){

  24.             //match just the IP address
  25.             var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
  26.             var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];

  27.             //remove duplicates
  28.             if(ip_dups[ip_addr] === undefined)
  29.                 callback(ip_addr);

  30.             ip_dups[ip_addr] = true;
  31.         }
  32.     };

  33.     //create a bogus data channel
  34.     pc.createDataChannel("");

  35.     //create an offer sdp
  36.     pc.createOffer(function(result){

  37.         //trigger the stun server request
  38.         pc.setLocalDescription(result, function(){}, function(){});

  39.     }, function(){});
  40. }

  41. //Test: Print the IP addresses into the console
  42. getIPs(function(ip){console.log(ip);});
复制代码
测试页面:https://diafygi.github.io/webrtc-ips/  
过段时间可能会取消签到功能了
您需要登录后才可以回帖 登录 | Join BUC

本版积分规则

Powered by Discuz!

© 2012-2015 Baiker Union of China.

快速回复 返回顶部 返回列表