首页 > 编程语言 >How to get the client IP address with Javascript only

How to get the client IP address with Javascript only

时间:2024-03-26 10:23:12浏览次数:33  
标签:function service get IP Javascript client ip

Learn how to get the client IP address (local and private) using only javascript.

articleocw-57dfeb2a430a6

Javascript is unable to get (nor stores somewhere) the client IP, however javascript is able to create Http requests, and server side languages are able to retrieve the user public IP, so you could use this as advantage. In other words, if you want to retrieve the public IP of an user you'll depend from a request to any server in order to retrieve the IP. You can easily get a VPS from the Best Node.js Hosting, deploy a simple JS Script, and publish it as a service with Node.js and Express JS so you can request this service, obtaining the IP of the client.

However, with the introduction of the WebRTC, you'll be able to retrieve the private IP of the user with a trick using RTCPeerConnection.

In this article you'll learn how to retrieve the user IP (private using pure javascript and public using a third party service) easily with a couple of tricks.

Using webRTC (get private IP)

The RTCPeerConnection interface allow you to create a WebRTC connection between your computer and a remote peer. However, we are going to create an "interrupted" version of it in order to retrieve the IP of the client using only javascript.

The createOffer method initiates the creation of a session description protocol (SDP) which offer information about any MediaStreamTracks attached to the WebRTC session, session, codes and any candidates already gathered by the ICE agents (which contains our goal, the IP).

In older versions, this method uses callbacks. However, now return a value based in a Promise that returns the information that we need when fullfilled:

Note: the pure javascript implementation will return the client private IP, not the public. Save this Snippet.

/**
 * Get the user IP throught the webkitRTCPeerConnection
 * @param onNewIP {Function} listener function to expose the IP locally
 * @return undefined
 */
function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
    //compatibility for firefox and chrome
    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    var pc = new myPeerConnection({
        iceServers: []
    }),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

    function iterateIP(ip) {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
    }

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

    // create offer and set local description
    pc.createOffer().then(function(sdp) {
        sdp.sdp.split('\n').forEach(function(line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(iterateIP);
        });
      
        pc.setLocalDescription(sdp, noop, noop);
    }).catch(function(reason) {
        // An error occurred, so handle the failure to connect
    });

    //listen for candidate events
    pc.onicecandidate = function(ice) {
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
    };
}

// Usage

getUserIP(function(ip){
    alert("Got IP! :" + ip);
});

The getUserIP​ method expects as first parameter a function that will be invoked when the IP of the client is available. The callbacks receives a string (the ip) as first (and unique) parameter. You can see the previous snippet in action via JSFiddle:

Using a third party service (get public IP)

If you need to provide cross-browser support, you'll be unable to use RTCPeerConnection to retrieve your client private IP, therefore the only resource you have it's to depend from an external service (a request to a server, third party service or your autoimplemented service in your own server).

Insecure connections HTTP

To get the IP of the user from a website without SSL certificate, you can rely on ipinfo.io. This service offers an API to get the client IP with a simple ajax call:

$.getJSON('http://ipinfo.io', function(data){
    console.log(data);
});

The retrieven data object contains localization info like : country, city etc when available. The servers of ipinfo use latency based DNS routing to handle the request so quick as possible. Read more about ipinfo in the official website here.

To get the IP of the user from a website even in secured websites with SSL, you can use the ipify service which provides a friendly API to get the user IP easily. This service has no request limitations.
You can use it in your project requesting to the API (with the format parameter if you need) and you're ready to go.

API URI Response Type Sample Output (IPv4) Sample Output (IPv6)
https://api.ipify.org text 11.111.111.111 ?
https://api.ipify.org?format=json json {"ip":"11.111.111.111"} ?
https://api.ipify.org?format=jsonp jsonp callback({"ip":"11.111.111.111"}); ?
https://api.ipify.org?format=jsonp&callback=getip jsonp getip({"ip":"11.111.111.111"}); ?

You can use it with JSONP:

<script type="application/javascript">
  function getIP(json) {
    document.write("My public IP address is: ", json.ip);
  }
</script>

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

Or retrieve an object with a json request using jQuery:

$.getJSON('https://api.ipify.org?format=json', function(data){
    console.log(data.ip);
});

Besides, you can create, in case you have your own server and you're able to work on it, create your own private service that returns the IP of the user with a server language like PHP,ASP.NET etc.

Have fun !

标签:function,service,get,IP,Javascript,client,ip
From: https://www.cnblogs.com/shenhuanjie/p/18096007/how-to-get-the-client-ip-address-with-javas

相关文章

  • 如何使用 JavaScript 导入和导出 Excel
    前言在现代的Web应用开发中,与Excel文件的导入和导出成为了一项常见而重要的任务。无论是数据交换、报告生成还是数据分析,与Excel文件的交互都扮演着至关重要的角色。本文小编将为大家介绍如何在熟悉的电子表格UI中轻松导入Excel文件,并以编程方式修改表格或允许用户进行编辑,最......
  • 54文章解读与程序——论文可在知网下载-含sop配电网重构+故障6-7+yalmip+二阶锥---已
    ......
  • nestJs中 Guards ,Interceptors ,Pipes ,Controller ,Filters的执行顺序
    执行顺序:Guards(守卫):Guards是最先执行的中间件,用于确定是否允许请求继续处理。Guards在请求被路由到控制器之前执行,通常用于身份验证、角色检查或权限验证。如果Guards返回一个布尔值 false 或者抛出一个异常,请求处理流程将终止,不会执行后续的Pipes、Interceptors或控......
  • C语言——getchar()
     //这里的代码适当修改是可以用来清理缓冲区的intmain(){ intch=0; while((ch=getchar())!=EOF) { putchar(ch); }return0;}intmain(){ //举一个例子 //假设密码是一个字符串 charpassword[20]={0}; printf("请输入密码:>"); scanf("%s......
  • TypeScript学习笔记之泛型
    介绍软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性。组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型,这在创建大型系统时为你提供了十分灵活的功能。在像C#和Java这样的语言中,可以使用泛型来创建可重用的组件,一个组件可以支持多种类型的数据......
  • P1525 [NOIP2010 提高组] 关押罪犯
    带权并查集中,dist[]数组可以理解为一个向量,这样子比按照距离来理解更透彻:优秀学习资料:AcWing240.食物链(带权并查集)-AcWing即d[a]表示向量a->fa[a]这道题的并查集解法:#include<iostream>#include<stdio.h>#include<algorithm>#include<string>#include<cmath>......
  • QtableWidget 表头增加复选框简单实现方法
    1.最近再开发一个批量查询上传的小工具,要增加一个批量选择的复选框,全选或者全不选;QCheckBox*checkBox=newQCheckBox(ui.tableWidget);checkBox->resize(40,24);ui.tableWidget->setCellWidget(0,0,checkBox);checkBox->setStyleSheet("margi......
  • Flink: Function And Rich Function , 对比 Function ,Rich functions还提供了这些方法:o
    Flink:FunctionAndRichFunction,对比Function,Richfunctions还提供了这些方法:open、close、getRuntimeContext和setRuntimeContext序言    了解了Flink提供的算子,那我们就可以自定义算子了.自定义算子的目的是为了更加灵活的处理我们的业务数据,并将满足条件......
  • IPv4网络地址
    1.IPv4网络地址范围和默认子网掩码公有网络地址(以下简称公网地址)是指在互联网上全球唯一的IP地址。A、1.0.0.1~126.255.255.254(有类边界)默认子网掩码/8,即255.0.0.0A类地址=网络部分+主机部分+主机部分+主机部分B、128.0.0.1~191.255.255.254(有类边界)默认子网掩码/16,即255.255......
  • Windows 防火墙中设置规则以拒绝所有流量,但允许特定 IP 通过
    在Windows防火墙中设置规则以拒绝所有流量,但允许特定IP通过,可以通过以下步骤进行设置:打开控制面板:点击“开始”按钮,然后输入“控制面板”并按回车键。打开WindowsDefender防火墙:在控制面板中,找到并点击“系统和安全”>“WindowsDefender防火墙”。设置......