You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * Get the user IP throught the webkitRTCPeerConnection * @param onNewIP {Function} listener function to expose the IP locally * @return undefined */functiongetUserIP(onNewIP){// onNewIp - your listener function for new IPs//compatibility for firefox and chromevarmyPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection;varpc=newmyPeerConnection({iceServers: []}),noop=function(){},localIPs={},ipRegex=/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,key;functioniterateIP(ip){if(!localIPs[ip])onNewIP(ip);localIPs[ip]=true;}//create a bogus data channelpc.createDataChannel("");// create offer and set local descriptionpc.createOffer().then(function(sdp){sdp.sdp.split('\n').forEach(function(line){if(line.indexOf('candidate')<0)return;line.match(ipRegex).forEach(iterateIP);});pc.setLocalDescription(sdp,noop,noop);}).catch(function(reason){// An error occurred, so handle the failure to connect});//listen for candidate eventspc.onicecandidate=function(ice){if(!ice||!ice.candidate||!ice.candidate.candidate||!ice.candidate.candidate.match(ipRegex))return;ice.candidate.candidate.match(ipRegex).forEach(iterateIP);};}// UsagegetUserIP(function(ip){alert("Got IP! :"+ip);});
<scripttype="application/javascript">functiongetIP(json){document.write("My public IP address is: ",json.ip);}</script><scripttype="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Have fun 🥇
The text was updated successfully, but these errors were encountered:
gnipbao
changed the title
使用JavaScript获取IP地址
如何使用JavaScript获取IP地址
Nov 21, 2017
JavaScript是无法获得或存储在客户端的IP。但是由于JavaScript能够发送HTTP请求,而服务器端语言能够获取用户的公网IP,所以你可以利用这个获取IP。 换句话说,如果你想得到一个用户就取决于请求任何服务器检索公网IP。 随着WebRTC技术的发展,利用rtcpeerconnection可以检索用户私有IP。
使用 webRTC (获取私有IP)
RTCPeerConnection技术详细可见MDN
使用第三方服务(获取公网IP)
可以使用jsonp形式在页面上。
Have fun 🥇
The text was updated successfully, but these errors were encountered: