Firefox 跟 Chrome支持WebRTC可以向STUN服务器请求,返回内外网IP,不同于XMLHttpRequest请求,STUN请求开发者工具当中看不到网络请求的。* F7 u& K( i9 U5 f" w8 g
, z8 d6 j% o4 M
//get the IP addresses associated with an account I2 L) b! y* t. ]
function getIPs(callback){
, j+ H: C. v! d7 z var ip_dups = {};9 s: y3 g; @1 {' o
$ D. q, B5 z5 X3 g | f* q //compatibility for firefox and chrome
' I' j* b+ N& ^ M! c var RTCPeerConnection = window.RTCPeerConnection" B: V% W, o! u5 F" M
|| window.mozRTCPeerConnection9 G; c- y) f; X- a r
|| window.webkitRTCPeerConnection;
- e6 _5 u4 d' l( ? F var mediaConstraints = {
. j3 q, d4 T5 @# ? optional: [{RtpDataChannels: true}]
* h* b; D# _( l };- z. f* k5 {# X. D- U9 O0 k* ~1 C
, g! Z% r8 f+ y# ?4 M0 g
//firefox already has a default stun server in about:config
0 B4 V* x8 K4 i5 G3 z- Y6 Y# } // media.peerconnection.default_iceservers =4 p- O0 |; ^ m3 ^
// [{"url": "stun:stun.services.mozilla.com"}]
+ a+ Z+ g# X1 E1 u5 U* Y& Q$ O! D var servers = undefined;
3 N; C a/ j' `: T# N
+ k3 Y1 B, }; z) I! {% K8 m6 K //add same stun server for chrome
/ X) P) m* [ N0 k0 L: n( `" k if(window.webkitRTCPeerConnection)
6 n2 U3 x, k3 @: C w8 B I servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
% {! @% u! m; @' h3 n $ J- A7 E+ {6 {! @' F4 c3 i* K
//construct a new RTCPeerConnection
( w' l* A4 p8 m) X7 [2 z' n+ ^ D var pc = new RTCPeerConnection(servers, mediaConstraints);5 T1 R2 w9 u" J
% [6 ~4 D3 A: S t5 G) k! _ //listen for candidate events; M# c) \ c7 s1 Z8 v3 j t' C
pc.onicecandidate = function(ice){
, P1 U, Z' {0 l 1 e8 I% j; f6 V& _* I
//skip non-candidate events
+ L( t/ }8 \8 A if(ice.candidate){( V. F" \! i& T3 k
: w% p4 N! Q2 S //match just the IP address! M( g( b# q) J5 I Y5 X
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/4 t+ i) ?9 f6 j
var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];3 [& u; S. ]& D: }
' k, f9 {- ^1 K. ~9 b0 x, M //remove duplicates
5 |$ P) [# H! c. \/ s( H+ p if(ip_dups[ip_addr] === undefined)
X9 `3 r5 q* R5 t/ u# ] callback(ip_addr);$ y9 I; m: b# |4 S6 _
6 I1 Z" x8 q0 c# z% K7 ?
ip_dups[ip_addr] = true; J0 C" G, i+ z4 D
}
& I: Y& K$ y9 n5 ^ };
) ~3 A$ U& T; ]9 _( B
( T7 U! O" }1 h //create a bogus data channel7 g' G8 b$ B" I+ a5 O( G" J' z2 Z- B
pc.createDataChannel("");
. c3 o4 f! T. K: R " [$ u( x* I: [% V2 L
//create an offer sdp
; R( z) x+ U0 v, \' z1 L7 z/ @, q pc.createOffer(function(result){. k6 J; E9 ^$ I+ a
K" m- z3 Y9 o. j( x. @ _$ @ //trigger the stun server request3 D, }) \7 P% e2 \7 s. S
pc.setLocalDescription(result, function(){});
, ~/ y" p) E; q7 a# v/ \
$ H; V) y8 L1 K. z* I# M }, function(){});
, D1 j) `/ N% m, \: P+ q" G3 P}0 U ]( @; x: W7 v+ a" z
& Y+ g: _3 l7 R' [
//Test: Print the IP addresses into the console( D S+ Z& f) {( M7 h7 B C
getIPs(function(ip){console.log(ip);}); |
|