前端H5开发,获取内网IP和公网IP
可直接打开,简答便捷,重要的事情说三遍
直接使用! 直接使用! 直接使用!
获取内网IP
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title></head><body><ul><li>内网ip</li></ul><script>function getIPs(callback) {var ip_dups = {};var RTCPeerConnection = window.RTCPeerConnection ||window.mozRTCPeerConnection ||window.webkitRTCPeerConnection;var useWebKit = !!window.webkitRTCPeerConnection;if (!RTCPeerConnection) {var iframe = document.createElement('iframe');iframe.style.display = 'none';iframe.sandbox = 'allow-same-origin';iframe.addEventListener("DOMNodeInserted", function(e) {e.stopPropagation();}, false);iframe.addEventListener("DOMNodeInsertedIntoDocument", function(e) {e.stopPropagation();}, false);document.body.appendChild(iframe);var win = iframe.contentWindow;RTCPeerConnection = win.RTCPeerConnection ||win.mozRTCPeerConnection ||win.webkitRTCPeerConnection;useWebKit = !!win.webkitRTCPeerConnection;}var mediaConstraints = {optional: [{RtpDataChannels: true}]};var servers = undefined;if (useWebKit)servers = {iceServers: [{urls: "stun:stun."}]};var pc = new RTCPeerConnection(servers, mediaConstraints);function handleCandidate(candidate) {var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/var ip_addr = ip_regex.exec(candidate)[1];if (ip_dups[ip_addr] === undefined)callback(ip_addr);ip_dups[ip_addr] = true;}pc.onicecandidate = function(ice) {if (ice.candidate)handleCandidate(ice.candidate.candidate);};pc.createDataChannel("");pc.createOffer(function(result) {pc.setLocalDescription(result, function() {}, function() {});}, function() {});setTimeout(function() {var lines = pc.localDescription.sdp.split('\n');lines.forEach(function(line) {if (line.indexOf('a=candidate:') === 0)handleCandidate(line);});}, 1000);}getIPs(function(ip) {var li = document.createElement("li");li.textContent = ip;if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) {//内网ipdocument.getElementsByTagName("ul")[0].appendChild(li);}});</script></body></html>
获取公网IP
通常我们使用搜狐的接口
<!DOCTYPE html><html><head><title>公网ip获取</title><meta http-equiv=Content-Type content="text/html; charset=gb2312"></head><body><script src="/cityjson?ie=utf-8"></script><script type="text/javascript">document.write(returnCitySN["cip"] + ',' + returnCitySN["cname"])</script></body></html>