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(Web Real-Time Communication)是一种支持浏览器之间实时通信的技术,可以通过创建一个 RTCPeerConnection 对象来获取本地网络接口信息。以下是一个示例代码: ```javascript let ipAddresses = []; // 创建一个新的 RTCPeerConnection 对象 let peerConnection = new RTCPeerConnection({ iceServers: [] }); // 当 ICE 候选生成时,提取其中的 IP 地址 peerConnection.onicecandidate = function (event) { if (event.candidate) { let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/g; let found = event.candidate.candidate.match(ipRegex); if (found && ipAddresses.indexOf(found[0]) === -1) { ipAddresses.push(found[0]); } } else { console.log("内网 IP 地址列表:", ipAddresses); } }; // 创建数据通道并触发 ICE 候选生成 peerConnection.createDataChannel(""); peerConnection.createOffer().then(offer => peerConnection.setLocalDescription(offer)); ``` 这种方法依赖于浏览器对 WebRTC 的支持,并且可能会受到某些浏览器的安全策略限制[^4]。 #### 方法二:通过操作系统 API 在 Node.js 环境下,可以使用 `os` 模块来获取本机的网络接口信息。以下是一个示例代码: ```javascript const os = require('os'); function getNetworkIp() { let needHost = ''; try { let network = os.networkInterfaces(); for (let dev in network) { let iface = network[dev]; for (let i = 0; i < iface.length; i++) { let alias = iface[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { needHost = alias.address; } } } } catch (e) { needHost = 'localhost'; } return needHost; } console.log("内网 IP 地址:", getNetworkIp()); ``` 此方法适用于服务器端或 Electron 应用程序中运行的 JavaScript 环境[^2]。 #### 方法三:通过外部服务 可以通过调用外部 API 来获取公网 IP 地址,但这种方法无法直接获取内网 IP 地址。例如: ```javascript function getPublicIP(json) { document.write("公网 IP 地址是: ", json.ip); } let script = document.createElement('script'); script.src = "https://api.ipify.org?format=jsonp&callback=getPublicIP"; document.body.appendChild(script); ``` 需要注意的是,Chrome 浏览器可能会隐藏内网 IP 地址,导致返回的结果为类似 `e87e041d-15e1-4662-adad-7a6601fca9fb.local` 的机器码[^3]。 ### 注意事项 - 使用 WebRTC 获取内网 IP 地址的方法可能不适用于所有浏览器,具体行为取决于浏览器的安全策略。 - 在前端环境中,直接获取内网 IP 地址通常需要用户授权或特定配置。 - 如果需要在浏览器中实现更可靠的解决方案,建议结合后端服务进行处理。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值