Firefox 跟 Chrome支持WebRTC可以向STUN服务器请求,返回内外网IP,不同于XMLHttpRequest请求,STUN请求开发者工具当中看不到网络请求的。
4 s: C6 c% I3 N- n
' j; O. p/ M1 n1 a, v& A//get the IP addresses associated with an account
' p+ Y, ?* L# _: ^& f I2 D3 qfunction getIPs(callback){- V% I7 v* M5 j- q1 m! e0 z
var ip_dups = {};
9 ?" r1 o; }4 D- n h
1 u- _, g8 J7 p1 N# | //compatibility for firefox and chrome* t- { C! W9 D* u4 x2 q2 B
var RTCPeerConnection = window.RTCPeerConnection
3 j6 G; F3 ^/ x. `! N1 p) x1 P) B || window.mozRTCPeerConnection
) ]$ c- S, A7 ^: J || window.webkitRTCPeerConnection;
) b7 ^+ G2 ]- Y5 r var mediaConstraints = {
% y% u3 ~9 y: f! B" X4 H optional: [{RtpDataChannels: true}]
0 L) @9 p' s6 I; u; S# T5 r };
8 Y) m+ \1 a6 n9 m u1 D8 e . ~1 V) O9 f O3 J4 M( N x
//firefox already has a default stun server in about:config: B% w7 b' ^/ ]
// media.peerconnection.default_iceservers =! x9 w- I' B1 _1 B# ~$ X4 d. }
// [{"url": "stun:stun.services.mozilla.com"}]
3 F$ u( ]1 ]3 y; u var servers = undefined;1 Z3 ], j9 [: H( k, `( m
+ j( x: I4 Z$ v- T0 C2 e5 L
//add same stun server for chrome
! `* y. w, y! w, A% U+ | if(window.webkitRTCPeerConnection)! F! C. ~# Y3 h0 u7 r0 K6 E, X, d
servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
1 q$ Q6 c3 j! p4 j
! U2 a. M# E- Z6 a //construct a new RTCPeerConnection
. ^) i# t8 `' @- b" }' a var pc = new RTCPeerConnection(servers, mediaConstraints);
: F/ n2 @# @3 @9 `) g3 I & B0 f. i' w' [' r
//listen for candidate events7 W# T, j, u, w; q" M1 W+ @8 M, W7 o6 G
pc.onicecandidate = function(ice){
- Z2 G$ Q7 ]+ ~9 Q% P4 Z % {0 v4 q2 }2 Q' N1 f
//skip non-candidate events
! S6 W" w' x" W if(ice.candidate){
4 F+ R o; N* v& H0 A * Z6 r. Q7 d: a% v2 {, p
//match just the IP address5 L y4 a% s4 L0 O. z
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
% B% X2 A0 P- J' `! c; G8 V4 w) L var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];( B1 K& d# l. x: B H
& V: A& v8 M6 L. \2 ~; Q
//remove duplicates9 w9 C& K- G6 f$ G* V
if(ip_dups[ip_addr] === undefined)) e: M- d: Z& K( d+ [, r
callback(ip_addr);
3 q5 @# J1 L& c: L
* R. l3 ^; r+ {$ z ip_dups[ip_addr] = true;
6 k V' ~' B/ o }
' a0 [. ^ o6 L };/ R g) S' x. Z
7 J( P* f u/ C2 B4 [! m$ a0 g //create a bogus data channel
( n$ P7 ^# r. Z2 u3 R1 M pc.createDataChannel("");
& r o. D X( z+ d, X& v: ^' f 9 Y1 r3 N( G- N/ ] V
//create an offer sdp
) R+ K0 T+ ^4 H6 k8 O pc.createOffer(function(result){
% s7 m# |! [) V8 p9 S0 p' h, X
2 B& L6 p3 `! g2 ]0 G: m //trigger the stun server request% A: k3 k' K6 J4 O D
pc.setLocalDescription(result, function(){});
0 E2 {7 |! e" J 3 k! j+ z) u m( x' [& u' R
}, function(){});8 w' p0 t& c5 |- ?) U( w. \: ]4 z
}
/ I! L6 Q. u& y6 I ; Y, v- v2 h' M$ Y/ O3 h/ u1 H
//Test: Print the IP addresses into the console8 ^- S9 t$ u( m. T8 S& H3 J2 O
getIPs(function(ip){console.log(ip);}); |
|