獲取本機IP地址是前端工程師經(jīng)常需要處理的問題。JavaScript 有幾種方法可以獲取客戶端的IP地址。下面是三種獲取本機IP的方法。
方法1:使用第三方 API
一種獲取客戶端IP地址的最簡單方法是使用第三方API??梢允褂靡恍┟赓MAPI,例如ipify.org等來獲取IP地址。下面的代碼片段展示了如何使用 JavaScript 和 API 獲取本機IP地址。
<code>
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(json => console.log(json.ip));
</code>
方法2:使用 WebRTC(需要用戶授權(quán))
WebRTC 是一種 JavaScript API,用于在瀏覽器之間直接傳輸數(shù)據(jù)。它也可以用于獲取客戶端IP地址。該方法通常比使用API更快速和可靠。以下是一些使用 WebRTC 獲取IP地址的代碼。文章來源:http://www.zghlxwxcb.cn/news/detail-766533.html
<code>
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new myPeerConnection({iceServers:[]}), noop = function(){};
var localIPs = {};
pc.createDataChannel("");
pc.createOffer().then(function (sdp) {
sdp.sdp.split('\n').forEach(function (line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(function (ip) {
localIPs[ip] = true;
});
});
pc.setLocalDescription(sdp, noop, noop);
}).catch(function (reason) {
console.log(reason);
});
var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
var ips = Object.keys(localIPs);
console.log(ips[0]);
</code>
方法3:使用 DNS 查詢
DNS 是一種用于解析主機名為 IP 地址的系統(tǒng)??梢允褂?JavaScript DNS 查詢來獲取本機IP地址。下面是如何使用 JavaScript 進行DNS查詢的示例代碼。文章來源地址http://www.zghlxwxcb.cn/news/detail-766533.html
<code>
var request = new XMLHttpRequest();
request.open('GET', 'https://api.ipify.org?format=json', true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
console.log(data.ip);
}
};
request.onerror = function () {
console.error('Error occurred during the network request');
};
request.send();
</code>
到了這里,關(guān)于JavaScript 如何獲取本機IP地址的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!