在JavaScript中获取当前页面的IP地址通常涉及到与服务器端的交互,因为客户端JavaScript本身无法直接获取本地网络接口的IP地址。以下是几种常见的方法来获取当前页面的IP地址:
你可以使用第三方提供的API服务来查询客户端的IP地址。例如,使用ipify服务:
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log('Your IP address is:', data.ip);
})
.catch(error => {
console.error('Error fetching IP:', error);
});如果你有自己的服务器,可以在服务器端获取客户端的IP地址,然后通过API返回给前端。
const express = require('express');
const app = express();
app.get('/get-ip', (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
res.json({ ip });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});fetch('/get-ip')
.then(response => response.json())
.then(data => {
console.log('Your IP address is:', data.ip);
})
.catch(error => {
console.error('Error fetching IP:', error);
});WebRTC(Web Real-Time Communication)也可以用来获取本地IP地址,但这通常用于P2P通信场景。
function getLocalIPs(callback){
var ips = [];
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({iceServers:[]});
pc.createDataChannel('');
pc.onicecandidate = function(e){
if (!e.candidate) {
pc.close();
callback(ips);
return;
}
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
if (ips.indexOf(ip) == -1){
ips.push(ip);
}
};
pc.createOffer().then(function(sdp){
pc.setLocalDescription(sdp);
}).catch(function(e){
console.error(e);
});
}
getLocalIPs(function(ips){
console.log('Your IP addresses:', ips);
});X-Forwarded-For头。以上方法可以帮助你在JavaScript中获取当前页面的IP地址,具体选择哪种方法取决于你的应用场景和需求。
没有搜到相关的文章