JavaScript获取客户端IP地址
JavaScript获取客户端IP地址
1. 第三⽅接⼝
2)
1 <script type="application/javascript">
2function getIP(json) {
3    document.write("My public IP address is: ", json.ip);
4  }
5 </script>
6
7 <script type="application/javascript" src="?format=jsonp&callback=getIP"></script>
或者
1 $.getJSON('?format=json', function(data){
2    console.log(data.ip);
3 });
2. 向服务器发送⼀个ajax请求,该请求包中会包含客户端的相关信息,当然也包括IP。
3. 使⽤webRTC,获取私有IP
1/**无法获取ip地址
2 * Get the user IP throught the webkitRTCPeerConnection
3 * @param onNewIP {Function} listener function to expose the IP locally
4 * @return undefined
5*/
6function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
7//compatibility for firefox and chrome
8var myPeerConnection = window.RTCPeerConnection || RTCPeerConnection || window.webkitRTCPeerConnection;
好段9var 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
17function iterateIP(ip) {
18if (!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) {
28if (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) {
39if (!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 });

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。