Firefox 跟 Chrome支持WebRTC可以向STUN服务器请求,返回内外网IP,不同于XMLHttpRequest请求,STUN请求开发者工具当中看不到网络请求的。
( l% S* a( R2 v2 J# b) i& e; L1 f2 }+ C
//get the IP addresses associated with an account
7 U- k3 T/ W4 Q+ `function getIPs(callback){
4 U5 J3 f; V! b& f1 F0 U var ip_dups = {};
* O) l% t( K& Y" o |2 E5 }4 p ! w5 T4 \( H$ h! Q3 B: B1 y7 Q
//compatibility for firefox and chrome9 X F. ^3 ^+ w2 ^
var RTCPeerConnection = window.RTCPeerConnection# f0 p) h$ H+ x8 R
|| window.mozRTCPeerConnection
5 a) F# G: g: |$ | || window.webkitRTCPeerConnection;( Z' k, Y" q1 k
var mediaConstraints = {
, E9 O% N; G) q# v/ G. o7 C% ` optional: [{RtpDataChannels: true}]
7 B% F3 Y$ O X- Q* B };
) ^0 t* I( `" p$ `0 i + O# q! L; V5 j) q' P# z$ s, y
//firefox already has a default stun server in about:config
$ s2 I1 |5 g) W1 g2 I5 V // media.peerconnection.default_iceservers =6 G8 y M* P- k" W% U
// [{"url": "stun:stun.services.mozilla.com"}]
v! g x) n" X, y var servers = undefined;
& |/ e5 o% D* ]3 d/ z
g3 u9 r4 E5 O, y* _6 b //add same stun server for chrome
$ Y! @% p; q( A6 u6 \ if(window.webkitRTCPeerConnection)
. ?; z3 I6 X' g( p' u1 N& ] servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};+ r2 A$ X: U. W7 s8 R' W5 V
# l( |3 G( s0 f
//construct a new RTCPeerConnection6 @4 {# {2 q7 f, Y- r9 f9 R0 ^
var pc = new RTCPeerConnection(servers, mediaConstraints);
; c5 l0 [ J2 \0 K, h% i
4 W- \! E6 F% c6 n$ ` //listen for candidate events! w ` Q$ a. J1 F
pc.onicecandidate = function(ice){* l: Y& U8 a' A z# T
$ N! H( d) M" V6 X //skip non-candidate events! l, E5 K ?9 x& ^8 I4 q7 z& `" k
if(ice.candidate){
( |9 V! \$ z$ o! Y; L
) [) P4 l; m6 r' G( \+ I- X //match just the IP address
+ s V: n9 \, p0 o/ w% g var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/: Z7 I! w- p/ ~" C. [* N8 [9 ~* }
var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];4 u. D6 c e! L! T& v0 W1 z1 A
( ?) }1 ]! n3 q$ N //remove duplicates) ^( X. h: y. ~2 j6 P
if(ip_dups[ip_addr] === undefined)
4 R8 Y' K- A s8 w( o( n callback(ip_addr);
3 h/ o0 K n: _( _1 i* g& u * W# k& ~2 z3 ^) ~5 C8 I
ip_dups[ip_addr] = true;
( S& y3 c* ], i; }. V }
& l5 |6 J: n W };
) y5 U. ?' q5 o- Z& M6 [: W! r$ X+ @ # A+ U3 T1 L8 ^
//create a bogus data channel
+ F+ v3 L3 A$ @ pc.createDataChannel("");! {; C1 Z$ N: z7 g. z) ^
+ a% F4 {* t' {+ k //create an offer sdp1 Y9 ^ f# A* O; i, m8 p; r* g
pc.createOffer(function(result){
" O: R" k! R7 O% g
& W( O( G' [, g9 Y* P/ [ //trigger the stun server request9 N5 W% ^4 P4 a6 }3 F4 L2 a
pc.setLocalDescription(result, function(){});
: F) u7 w7 [$ s W: g1 t2 b7 D $ Q' D; {- B9 t
}, function(){});
% l. n, f# h0 t}/ S1 K8 D' L5 M7 ~7 ?
8 m Z. d) N6 q9 r
//Test: Print the IP addresses into the console0 ^# Z% V, j+ ?" k& O
getIPs(function(ip){console.log(ip);}); |
|