// 使用RTCPeerConnection和stun服务器获取公网IP地址
function getPublicIP() {
return new Promise((resolve, reject) => {
const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) {
const rtc = new RTCPeerConnection({ iceServers: [] });
rtc.createDataChannel('', { reliable: false });
rtc.onicecandidate = function (evt) {
if (evt.candidate) {
const ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
const ip_addr = ip_regex.exec(evt.candidate.candidate)[1];
rtc.onicecandidate = null;
rtc.close();
resolve(ip_addr);
}
};
rtc.createOffer(function (offerDesc) {
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("oops... something went wrong:", e); });
} else {
reject(null);
}
})
}