找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 拇指 mztk
查看: 3291|回复: 0

WEB端获取内网IP地址,JS获取局域网IP地址

[复制链接]

33

主题

20

回帖

1910

积分

锦衣卫

积分
1910
QQ
发表于 2023-9-12 18:25:34 | 显示全部楼层 |阅读模式
本帖最后由 mz535310 于 2023-9-12 18:30 编辑

//获取内网网IP
function getIPs(callback){
    let ip_dups = {};
    let RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
        || window.webkitRTCPeerConnection;
    letuseWebKit = !!window.webkitRTCPeerConnection;

    if(!RTCPeerConnection){
        let win = iframe.contentWindow;
        RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
            || win.webkitRTCPeerConnection;
        useWebKit = !!win.webkitRTCPeerConnection;
    }
    let mediaConstraints = {optional: [{RtpDataChannels: true}]};
    let 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
let ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
        let ip_addr = ip_regex.exec(candidate)[1];
        if(ip_dups[ip_addr] === undefined)
            callback(ip_addr);
        ip_dups[ip_addr] = true;
    }
    pc.onicecandidate = function(ice){
        //skip non-candidate events
if(ice.candidate)
            handleCandidate(ice.candidate.candidate);};
    pc.createDataChannel("");
    pc.createOffer(function(result){
        pc.setLocalDescription(result, function(){}, function(){});
    }, function(){});

    setTimeout(function(){
        let lines = pc.localDescription.sdp.split('\n');
        lines.forEach(function(line){
            if(line.indexOf('a=candidate:') === 0)
                handleCandidate(line);
        });
    }, 1000);
}

//使用方法//获取内网IP
getIPs(function(gnips){
    //我要内网IP
if (gnips.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) {
        localStorage.setItem('gnip', gnips);
        console.log("内网IP:",gnips);
    }
});




//关键说明,以上配置需要浏览器启用插件,启用说明请链接点击查看

chrome edge浏览器开启IPV4
https://www.mztk.cc/forum.php?mod=viewthread&tid=36099
(出处: 拇指天空)


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|再加计算机 ( 鲁ICP备19060125号-10|鲁公网安备37028102001711号 )

GMT+8, 2026-9-11 17:54 , Processed in 0.115809 second(s), 24 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表