如何用js获取ip地址
admin 阅读:116 2024-06-08
获取 ip 地址的方法:直接获取webrtc api。使用 navigator.mediadevices.getusermedia()。通过服务器代理发送 ajax 或 fetch 请求。

如何用 JavaScript 获取 IP 地址
直接获取
- WebRTC API
async function getIP() {
const configuration = {
iceServers: [
{
urls: ['stun:stun.l.google.com:19302']
}
]
};
const peerConnection = new RTCPeerConnection(configuration);
const iceCandidate = await new Promise((resolve) => {
peerConnection.onicecandidate = (e) => {
if (e.candidate && e.candidate.type === 'srflx') {
resolve(e.candidate.address);
}
};
});
peerConnection.close();
return iceCandidate;
}- navigator.mediaDevices.getUserMedia()
async function getIP() {
const mediaStream = await navigator.mediaDevices.getUserMedia({ video: false, audio: false });
const peerConnection = new RTCPeerConnection();
const sender = peerConnection.addTrack(mediaStream.getTracks()[0], mediaStream);
const iceCandidate = await new Promise((resolve) => {
peerConnection.onicecandidate = (e) => {
if (e.candidate && e.candidate.type === 'srflx') {
resolve(e.candidate.address);
}
};
});
sender.stop();
peerConnection.close();
return iceCandidate;
}通过服务器代理
- 使用 AJAX 或 fetch
向服务器发送请求,服务器响应中包含 IP 地址。
async function getIP() {
const response = await fetch('/get-ip');
const data = await response.json();
return data.ip;
}注意事项
- WebRTC API 和 navigator.mediaDevices.getUserMedia() 只能在安全连接(HTTPS)上使用。
- 服务器代理方法需要后端支持。
- 获取到的 IP 地址可能是本地 IP 地址,而不是外部 IP 地址。
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



