如何使用JavaScript获取本地/内部IP [英] How to get local/internal IP with JavaScript

查看:1079
本文介绍了如何使用JavaScript获取本地/内部IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 WebRTC 获取本地客户端IP.

How can I get the local client IP using WebRTC.

我不需要客户端的REMOTE_ADDR,但是他的本地IP. 我以前在sharedrop.com这样的网站上已经看到过这一点,它可以使用WebRTC识别同一网络中的计算机.

I don't need the REMOTE_ADDR of the client but his local network IP. I've seen this before on websites like sharedrop.com, it recognizes computer within the same network using WebRTC.

在PHP中,我这样做是为了使客户端获得远程IP:

In PHP I do this to get the clients remote IP:

<?php
  echo $_SERVER["REMOTE_ADDR"]; // which would return 72.72.72.175
?>

我查看了stackoverflow,但是每个问题都可以通过远程地址来回答.

I looked through stackoverflow but every question is answered using the remote addr.

如何使用JavaScript而不是远程地址来获取本地IP(例如192.168.1.24).

How can I get my local IP (192.168.1.24 for example) with JavaScript instead of the remote addr.

推荐答案

我从-> 那里获取代码的地方

where I took code from --> Source

您可以在-> 演示

我已经修改了源代码,减少了行数,没有发出任何眩晕请求,因为您只希望本地IP而不是公共IP,以下代码在最新的Firefox和Chrome中有效:

I have modified the source code, reduced the lines, not making any stun requests since you only want Local IP not the Public IP, the below code works in latest Firefox and Chrome:

    window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;   //compatibility for firefox and chrome
    var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};      
    pc.createDataChannel("");    //create a bogus data channel
    pc.createOffer(pc.setLocalDescription.bind(pc), noop);    // create offer and set local description
    pc.onicecandidate = function(ice){  //listen for candidate events
        if(!ice || !ice.candidate || !ice.candidate.candidate)  return;
        var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
        console.log('my IP: ', myIP);   
        pc.onicecandidate = noop;
    };

这里发生的事情是,我们正在创建一个虚拟对等连接,并且为了使远程对等方与我们联系,我们通常会相互交换ice候选对象.并阅读冰候选人,我们可以告诉用户的ip.

what is happening here is, we are creating a dummy peer connection, and for the remote peer to contact us, we generally exchange ice candidates with each other. And reading the ice candiates we can tell the ip of the user.

这篇关于如何使用JavaScript获取本地/内部IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆