Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 获取本机ip

作者:昂首向前走,   发布日期:2025-12-14   浏览:71

// 获取本机IP的代码示例

// 使用 WebRTC 方式获取本机 IP 地址
function getLocalIP() {
    return new Promise((resolve, reject) => {
        const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        if (!RTCPeerConnection) {
            reject('RTCPeerConnection is not supported');
            return;
        }

        const pc = new RTCPeerConnection({ iceServers: [] });
        pc.createDataChannel('');

        pc.onicecandidate = (e) => {
            try {
                if (e.candidate) {
                    const ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
                    const ip_address = ip_regex.exec(e.candidate.candidate)[1];
                    resolve(ip_address);
                    pc.close();
                }
            } catch (err) {
                reject(err);
            }
        };

        pc.createOffer().then((sdp) => {
            pc.setLocalDescription(sdp);
        }).catch(reject);
    });
}

// 调用函数并处理结果
getLocalIP().then(ip => {
    console.log('本机IP地址:', ip);
}).catch(error => {
    console.error('获取IP地址失败:', error);
});

解释说明:

  1. RTCPeerConnection:这是 WebRTC 的一部分,用于创建点对点连接。通过它我们可以获取到本地网络接口的 IP 地址。
  2. onicecandidate 事件:当 ICE(Interactive Connectivity Establishment)候选者可用时触发。这些候选者包含了本地 IP 地址信息。
  3. 正则表达式:用于从候选者的字符串中提取出 IP 地址。
  4. Promise:为了方便异步操作,我们将整个过程封装在一个 Promise 中。

请注意,这种方法依赖于浏览器支持 WebRTC,并且可能在某些情况下无法获取到真实的公网 IP 地址,而只是局域网内的 IP 地址。

上一篇:js 数组函数

下一篇:js 二维码生成

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站