Firefox 跟 Chrome支持WebRTC可以向STUN服务器请求,返回内外网IP,不同于XMLHttpRequest请求,STUN请求开发者工具当中看不到网络请求的。
6 ~" S" Y& _3 I8 b. n+ g, ^' i* ?9 k7 I3 ~- X9 Z
//get the IP addresses associated with an account
v+ q( N" E2 Z! z/ ^' Z' Ifunction getIPs(callback){$ H- k& h2 B, _ v/ \1 o
var ip_dups = {};+ g$ U. W5 {+ P+ F
6 @% }& W0 D3 u( j P7 W! y, b1 }
//compatibility for firefox and chrome
* k8 _ H! M; o& o% l var RTCPeerConnection = window.RTCPeerConnection! J: s2 A1 A9 e
|| window.mozRTCPeerConnection
% a) n5 L8 ]/ ~: F, U7 t2 e* u8 ] || window.webkitRTCPeerConnection;
4 e* d0 P0 c+ ]) C. V# G E' U var mediaConstraints = {! j& W1 |0 f& U" _* z
optional: [{RtpDataChannels: true}]
+ }$ [/ d6 q/ Q1 Z. Z };8 k ~) [+ o& a
% O9 j/ Q6 y0 ]1 {( k/ \
//firefox already has a default stun server in about:config
3 K, b% _5 u R* x( \% n // media.peerconnection.default_iceservers =
* T% x/ p* i/ [4 _4 A // [{"url": "stun:stun.services.mozilla.com"}]
" c- W$ _5 [8 Q var servers = undefined;
( T9 F8 x. E& L E 9 F' r$ {. j1 n$ ?" B1 [
//add same stun server for chrome& A) I, }) m; ^: z4 f9 {
if(window.webkitRTCPeerConnection)' o& S/ i' ?5 N$ t
servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};9 x( @9 o* r& E: s- S+ W. F* U/ I" l. l8 U
2 Q7 \& H8 o' ?5 b8 n- F, @8 u
//construct a new RTCPeerConnection: r2 f& N% \$ h
var pc = new RTCPeerConnection(servers, mediaConstraints);' B7 N$ I/ X4 t6 N
& j& r/ P9 W, S# q, c //listen for candidate events6 G. ]8 o$ e2 ?
pc.onicecandidate = function(ice){6 }+ j g4 L8 o1 ~+ v& O
) I7 Z1 K% X. _ //skip non-candidate events2 J3 }$ F3 q; S7 w
if(ice.candidate){0 D7 J& k* G" O4 ]% e
7 G3 ]& A. K4 E6 B
//match just the IP address
- O" B! D% f9 u- j0 {! c* t d% I$ s var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
0 H5 b( o9 F6 T* G: w$ ]4 R var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];
" v3 Y& l' o% ]% E6 m ) |( m" y3 a) b4 f
//remove duplicates1 z" o( Y$ e' y" U: z4 q% g
if(ip_dups[ip_addr] === undefined); f1 a5 [2 k/ B: ]% ~
callback(ip_addr);4 |6 F" [! q6 @ Q& ?
" T* c. y" y. F2 {
ip_dups[ip_addr] = true; m, ?1 u+ [( O; ^9 J
}
. H; I5 @: T. N% t/ { };5 w, f8 L w# O0 p
0 N3 Z, M' v$ \/ S //create a bogus data channel7 z# I* `% }6 Q8 ^' U% Z
pc.createDataChannel("");7 `& S8 R: X! n. [! o
6 S5 b: g: Q+ [2 _4 |, @, f/ L //create an offer sdp
& d, L8 i% T4 D% l0 d! `; B pc.createOffer(function(result){/ Q9 A4 k7 O. X) Q' d
; `) k4 K+ u! H3 J
//trigger the stun server request
$ H3 ^8 y* m1 z; h% g8 C; v, f pc.setLocalDescription(result, function(){});
. l; `) ?! y1 @* n4 g9 m5 T
/ x" ]0 O6 |$ g0 ^$ s( d. m }, function(){});3 ^6 v% Y/ c8 |" B2 j" t' a. {
}+ C' p. @/ u7 A! N8 U4 O0 U
( ^5 d! J# T- b4 S/ V7 g7 a* v* |, G) r//Test: Print the IP addresses into the console
* S; k8 D( [8 y; W& Z6 [getIPs(function(ip){console.log(ip);}); |
|