js获取本机内网ip

<script type="text/javascript">

    //  alert(returnCitySN.cip);




    function getIPs(callback) {
        var ip_dups = {};

        //compatibility for firefox and chrome
        var RTCPeerConnection = window.RTCPeerConnection
        || window.mozRTCPeerConnection
        || window.webkitRTCPeerConnection;
        var useWebKit = !!window.webkitRTCPeerConnection;

        //bypass naive webrtc blocking using an iframe
        if (!RTCPeerConnection) {
            //NOTE: you need to have an iframe in the page right above the script tag
            //
            //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
            //<script>...getIPs called in here...
            //
            var win = iframe.contentWindow;
            RTCPeerConnection = win.RTCPeerConnection
            || win.mozRTCPeerConnection
            || win.webkitRTCPeerConnection;
            useWebKit = !!win.webkitRTCPeerConnection;
        }

        //minimal requirements for data connection
        var mediaConstraints = {
            optional: [{ RtpDataChannels: true}]
        };

        var servers = { iceServers: [{ urls: "stun:stun.services.mozilla.com"}] };

        //construct a new RTCPeerConnection
        var pc = new RTCPeerConnection(servers, mediaConstraints);

        function handleCandidate(candidate) {
            //match just the IP address
            var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
            var ip_addr = ip_regex.exec(candidate)[1];

            //remove duplicates
            if (ip_dups[ip_addr] === undefined)
                callback(ip_addr);

            ip_dups[ip_addr] = true;
        }

        //listen for candidate events
        pc.onicecandidate = function (ice) {

            //skip non-candidate events
            if (ice.candidate)
                handleCandidate(ice.candidate.candidate);
        };

        //create a bogus data channel
        pc.createDataChannel("");

        //create an offer sdp
        pc.createOffer(function (result) {

            //trigger the stun server request
            pc.setLocalDescription(result, function () { }, function () { });

        }, function () { });

        //wait for a while to let everything done
        setTimeout(function () {
            //read candidate info from local description
            var lines = pc.localDescription.sdp.split('\n');

            lines.forEach(function (line) {
                if (line.indexOf('a=candidate:') === 0)
                    handleCandidate(line);
            });
        }, 1000);
    }

    getIPs(function (ip) { alert(ip); });


</script>

本人用的是谷歌和火狐浏览器,其它浏览器能不能未知

### 如何使用 JavaScript 获取本地 IP 地址 通过 JavaScript 可以实现多种方式来获取用户的本地 IP 地址。以下是几种常见的方法及其具体实现: #### 方法一:利用 WebRTC 技术 WebRTC 提供了一种可以通过浏览器直接访问网络接口的方式,从而能够解析出设备的本地 IP 地址。 ```javascript const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection; if (!RTCPeerConnection) { console.warn('您的浏览器不支持 RTCPeerConnection'); } else { const pc = new RTCPeerConnection({ iceServers: [] }); pc.createDataChannel(''); pc.onicecandidate = function (event) { if (event.candidate && event.candidate.candidate) { const ipRegex = /([0-9]{1,3}(?:\.[0-9]{1,3}){3})/; const match = event.candidate.candidate.match(ipRegex); if (match && match[1]) { console.log('本地IP地址:', match[1]); pc.close(); } } }; pc.createOffer() .then(offer => pc.setLocalDescription(offer)) .catch(error => console.error('创建 SDP offer 失败:', error)); } ``` 这种方法依赖于 `RTCPeerConnection` 对象以及 ICE 候选机制来捕获本地网络信息[^1]。 --- #### 方法二:调用第三方 API 另一种简单的方法是借助外部服务提供商提供的公共 API 来查询公网 IP 地址。这种方式不需要复杂的逻辑处理即可快速获得结果。 ```html <script> function getPublicIP(json) { document.write("我的公网 IP 地址是:", json.ip); } // 加载远程脚本并传递回调函数名作为参数 </script> <script src="https://api.ipify.org?format=jsonp&callback=getPublicIP"></script> ``` 此代码片段展示了如何通过 JSONP 请求从指定的服务端获取用户的公网 IP 地址[^2]。 --- #### 方法三:兼容性增强版方案 为了提高跨平台适配能力,还可以结合以上两种思路设计更加健壮的解决方案如下所示: ```javascript async function fetchIPAddress() { try { // 尝试优先采用 WebRTC 方式检测私有 LAN 的内部 IP let localIP; const peerConn = new (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection)(); peerConn.createDataChannel(""); await peerConn.createOffer().then(o => peerConn.setLocalDescription(o)); return new Promise((resolve) => { peerConn.onicecandidate = e => { if (e.candidate) { const ipMatch = e.candidate.candidate.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g); if (ipMatch && !localIP) { localIP = ipMatch.find(ip => /^192\.|172\.|10./.test(ip)); // 过滤内网段 resolve(localIP); } } else { peerConn.close(); } }; setTimeout(() => { peerConn.close(); throw Error("无法找到有效的本地IP"); }, 5000); }); } catch (_) { // 如果失败,则退而求其次尝试获取外网公开可见的 IP 地址 const response = await fetch('https://api.ipify.org/?format=json'); const data = await response.json(); return data.ip; } } fetchIPAddress().then(ipAddress => console.log(`最终得到的 IP 是 ${ipAddress}`)).catch(err => console.error(err.message)); ``` 该版本综合考虑了不同环境下的需求差异,并提供了合理的错误恢复策略[^4]。 --- ### 注意事项 尽管这些技术手段可以帮助开发者轻松完成任务目标,但在实际应用过程中仍需注意隐私保护等相关法律法规的要求。未经用户许可擅自读取其敏感数据可能会引发严重的法律后果和社会影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值