
最简单的方法是使用第三方API。这些API提供获取IP地址的功能,您只需要简单地发送一个HTTP请求即可。例如,您可以使用"ipify"API,代码如下:
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log('IP Address:', data.ip);
})
.catch(error => {
console.error('Error:', error);
});
另一种方法是使用WebRTC(Web Real-Time Communication)技术。WebRTC允许浏览器直接与其他客户端进行点对点的连接,在这个过程中会获取到客户端的IP地址。以下是一个简单的示例代码:
function getIPAddress() {
return new Promise((resolve, reject) => {
const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
const pc = new RTCPeerConnection({ iceServers: [] });
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), reject);
pc.onicecandidate = event => {
if (event.candidate) {
const ip = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(event.candidate.candidate)[1];
pc.onicecandidate = null;
resolve(ip);
}
};
});
}
这种方法需要注意的是,在某些情况下可能无法获取到完整的IP地址,例如在使用VPN或其他代理时。