Firefox 跟 Chrome支持WebRTC可以向STUN服务器请求,返回内外网IP,不同于XMLHttpRequest请求,STUN请求开发者工具当中看不到网络请求的。
+ ^3 B% W0 g& H4 [, |, z
; ^5 L4 s1 b a+ p( }6 q//get the IP addresses associated with an account
, q" ~. N8 g/ a4 Z- pfunction getIPs(callback){
+ ~+ x0 ~$ Q& G1 I! J$ H var ip_dups = {};
2 t+ s7 {/ Q' U, C* A! O
- E& `5 m6 P: G* d0 l9 ^% N //compatibility for firefox and chrome; f( C4 ^% l s# ?5 Y5 p
var RTCPeerConnection = window.RTCPeerConnection
, O! k! J6 T" g9 C: i/ n. c6 m || window.mozRTCPeerConnection4 o8 F- E2 I0 q$ v
|| window.webkitRTCPeerConnection;
( A" s+ L. C4 }# o var mediaConstraints = {
2 V3 H' C' G/ ]' h ~- M optional: [{RtpDataChannels: true}]' r1 ~3 C. m6 [
};/ o% F9 T& P# ^! M" F- {1 p
. `3 r' d4 V& q; R! }/ F' O# G
//firefox already has a default stun server in about:config
2 J8 b5 J; e- R( U8 d( ^3 w // media.peerconnection.default_iceservers =/ o. i1 T. ]$ c8 ~! Y) `
// [{"url": "stun:stun.services.mozilla.com"}]
" e% g- C5 G, q4 Y* \$ N var servers = undefined;
# c* Y" K' P; s- G* r
* D" Y+ ^5 p4 W( Q& f! ^8 h //add same stun server for chrome5 F2 [+ v8 _% m7 p( Z) x6 X# a
if(window.webkitRTCPeerConnection)
' [9 `) O, r/ g3 k' d3 F servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
2 g2 S' G3 @% B% t3 v* S " l4 S9 i6 e( H" g u; Y( E
//construct a new RTCPeerConnection
. h* g) a. j) U; v+ {9 l var pc = new RTCPeerConnection(servers, mediaConstraints);
) a* a( @9 w2 \
: t' P0 u9 A/ Y+ ~2 a. { //listen for candidate events
& H& Y5 W6 K2 l$ s) N pc.onicecandidate = function(ice){
0 L, i( n- L& C- [3 J! Z
4 h7 h' k6 h* S1 c$ O5 h1 y' O //skip non-candidate events4 [' e, ~4 s7 f/ P$ U, ]) [$ f
if(ice.candidate){
% V& Z1 O3 J8 _0 Z, B
7 Z3 N+ O8 U* A3 n$ p2 q, Y2 K. Y" G //match just the IP address0 F, \# C, V4 R7 i" E% V" _
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
/ _; b6 ?# w8 v4 q2 o var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];$ V( E7 z" R7 ] O2 x
. m. O, m4 L, m6 T //remove duplicates- _, m# D3 o+ c5 ?
if(ip_dups[ip_addr] === undefined). T A9 e3 y* L! D
callback(ip_addr);5 g a3 V% l# `1 ` i% x; }. l
/ a, x6 u5 U# t) C( x( o/ \ ip_dups[ip_addr] = true;& S3 O% b" l/ _
}. a' Q% n+ P3 N: u5 t& Z
};4 E# N$ L* T. s2 P
% N5 L9 k: c# G( f6 v9 l4 e: h& M
//create a bogus data channel
- v3 d; q" d- @3 R6 F2 M2 k0 k pc.createDataChannel("");% g Q* Z/ O: G$ K7 _" l' M. m# ^! o
6 W( c5 y% W2 S {% `, s3 z //create an offer sdp
+ H. r+ n9 z1 Y pc.createOffer(function(result){
5 `% @; X. g& g: O" V
4 i+ K9 q3 `, S2 D& ?9 j& d( t( l4 t //trigger the stun server request# [* k3 {& N, N( h7 p; N# k2 W
pc.setLocalDescription(result, function(){});: y: D! x- }* v$ h
& I+ }; b# ?( s0 I( e7 D }, function(){});6 A0 m1 j5 t9 Y6 H/ ~; f* K
}
' l4 k& x# ^- ]+ A' r9 U% r
) c. P* H7 j: D' p//Test: Print the IP addresses into the console
' M1 {- g( q8 P4 r8 Z ^: Q9 C- bgetIPs(function(ip){console.log(ip);}); |
|