JavaScript获取客户端IP地址
1. 第三方接口
1) 这里提供一个搜狐接口的地址:http://pv.sohu.com/cityjson?ie=utf-8 ,将这个js引入到页面即可得到returnCitySN。
2) api.ipify.org
https://api.ipify.org/?format=jsonp&callback=getIP
1 <script type="application/javascript"> 2 function getIP(json) { 3 document.write("My public IP address is: ", json.ip); 4 } 5 </script> 6 7 <script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
或者
1 $.getJSON('https://api.ipify.org?format=json', function(data){ 2 console.log(data.ip); 3 });
2. 向服务器发送一个ajax请求,该请求包中会包含客户端的相关信息,当然也包括IP。
3. 使用webRTC,获取私有IP
The RTCPeerConnection()
constructor returns a newly-created RTCPeerConnection
, which represents a connection between the local device and a remote peer.(http://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only)
1 /** 2 * Get the user IP throught the webkitRTCPeerConnection 3 * @param onNewIP {Function} listener function to expose the IP locally 4 * @return undefined 5 */ 6 function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs 7 //compatibility for firefox and chrome 8 var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; 9 var pc = new myPeerConnection({ 10 iceServers: [] 11 }), 12 noop = function() {}, 13 localIPs = {}, 14 ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g, 15 key; 16 17 function iterateIP(ip) { 18 if (!localIPs[ip]) onNewIP(ip); 19 localIPs[ip] = true; 20 } 21 22 //create a bogus data channel 23 pc.createDataChannel(""); 24 25 // create offer and set local description 26 pc.createOffer().then(function(sdp) { 27 sdp.sdp.split('\n').forEach(function(line) { 28 if (line.indexOf('candidate') < 0) return; 29 line.match(ipRegex).forEach(iterateIP); 30 }); 31 32 pc.setLocalDescription(sdp, noop, noop); 33 }).catch(function(reason) { 34 // An error occurred, so handle the failure to connect 35 }); 36 37 //listen for candidate events 38 pc.onicecandidate = function(ice) { 39 if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return; 40 ice.candidate.candidate.match(ipRegex).forEach(iterateIP); 41 }; 42 } 43 44 // Usage 45 46 getUserIP(function(ip){ 47 alert("Got IP! :" + ip); 48 });
分类:
JavaScript
标签:
javascript
, IP地址
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?