一,外網(wǎng):
html引入
<script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
//獲取外網(wǎng)ip方式1:搜狐
getIpBysouhu();
//獲取外網(wǎng)ip方式2:ipify
getIpByIpify();
// });
// //獲取外網(wǎng)ip方式1:搜狐
function getIpBysouhu() {
console.log("---外cip---" + returnCitySN["cip"]);
console.log("---外cid---" + returnCitySN["cid"]);
console.log("---外cname---" + returnCitySN["cname"]);
}
//獲取外網(wǎng)ip方式2:ipify
function getIpByIpify() {
$.ajax({
url: "https://api.ipify.org/?format=json",
type: "GET",
data: {},
dataType: "json",
success: function(result) {
console.log("---外ip---" + result.ip);
},
error: function() {
}
});
}
二.內(nèi)網(wǎng) 此方法在手機端無效
內(nèi)網(wǎng)IP的獲取相對比較復(fù)雜,主要是需要依賴 webRTC 這么一個非常用的API
WebRTC,名稱源自網(wǎng)頁即時通信(英語:Web Real-Time Communication)的縮寫,是一個支持網(wǎng)頁瀏覽器進行實時語音對話或視頻對話的API。它于2011年6月1日開源并在Google、Mozilla、Opera支持下被納入萬維網(wǎng)聯(lián)盟的W3C推薦標準。
webRTC 是HTML 5 的一個擴展,允許去獲取當(dāng)前客戶端的IP地址,可以查看當(dāng)前網(wǎng)址:http://net.ipcalf.com/
如果使用 chrome 瀏覽器打開,此時可能會看到一串類似于:`e87e041d-15e1-4662-adad-7a6601fca9fb.local 的機器碼,這是因為chrome 默認是隱藏掉 內(nèi)網(wǎng)IP地址的,可以通過修改 chrome 瀏覽器的配置更改此行為:
在chrome 瀏覽器地址欄中輸入:chrome://flags/
搜索#enable-webrtc-hide-local-ips-with-mdns 該配置 并將屬性改為disabled
參考:http://www.itdecent.cn/p/8d7348bc84f4
var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection)(function() {
var rtc = new RTCPeerConnection({
iceServers: []
});
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', {
reliable: false
});
};
rtc.onicecandidate = function(evt) {
if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function(offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function(e) {
console.warn("offer failed", e);
});
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function(k) {
return addrs[k];
});
for (var i = 0; i < displayAddrs.length; i++) {
if (displayAddrs[i].length > 16) {
displayAddrs.splice(i, 1);
i--;
}
}
console.log("---內(nèi)----" + displayAddrs[0]); //打印出內(nèi)網(wǎng)ip
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function(line, index, arr) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})();
else {
console.log("請使用主流瀏覽器:chrome,firefox,opera,safari");
}