Как получить ip человека в js

от admin

Read the User’s IP address in JavaScript

It can be quite handy for some projects to know the IP address of the client. However, this is not available in Javascript and can not be found out without external resources. Since I needed to find out the IP address of the client in Javascript for a project, I built a small solution for it and I am sharing my approach here.

The script will always return the current IP address of the client. Nothing more. Still, a function that can’t be solved client-side by default, but an external resource has to be requested.

Use cases

  • Redirect GA hits to another property based on IP, e.g. office IP
  • Do not run marketing pixel if IP is own office
  • Create a hash of the IP to use as an ID
  • and much more..

Set up in Google Cloud as Cloud Function

(or any other Node JS environment)

Since the only logic the script needs to do is answer with the requesters IP, the code is very short. The following snippet will return the IP address in JSON format. The code can be executed by a Node.js 12 Cloud Function instance.

Working example

The following script URL and code snippets are working. Kindly use it only for testing and development purposes. Don't use it on production. I might take it offline at any time.

How to get the client IP address with Javascript only

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

How to get the client IP address with Javascript only

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. 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.

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:

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.

Secure connections HTTPS (recommended)

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 ?
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:

Or retrieve an object with a json request using jQuery:

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.

Carlos Delgado

Carlos Delgado

Senior Software Engineer at EPAM Anywhere. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

How to Get the IP Address in JavaScript

To most people, an IP address is just that—the address of a device on the internet. But for application developers, it is an incredibly valuable piece of information. Over the years, countless bytes of information have been collected and cataloged about almost every device that has accessed the internet, and by using ipdata’s API, application developers can access a tremendous amount of location-oriented data to enhance their users’ experience.

But of course, you need an IP address before you can use the wealth of information provided by ipdata. In this article, you will learn how to retrieve an IP addresses with JavaScript—both from within the browser and in your server application.

Retrieving Your User’s IP in the Browser

The browser is the OS of the web, and with more processing being handled within the browser, it makes some sense to retrieve the user’s IP address so that you can use it in your client-side code. The problem, however, is that the browser doesn’t expose any network-oriented information about the device.

1. Using ipdata

You must therefore rely upon a web service to provide that information for you. You could write your own service as part of your server-side application, or you can use a third-party solution to retrieve your user’s IP address. ipdata’s web service is a perfect solution for this problem. All you need is an API key (go ahead and sign up for free). For example:

This code defines a helper function called json() . It simplifies the process of using fetch() with resources that return a JSON structure, as most APIs do. Next, the json() function is used to send a GET request to ipdata’s default endpoint: http://api.ipdata.co. You can use this endpoint to query any IP address, but if you do not provide one with the request, the web service uses the address of the device that issued the request: the browser in this case.

The web service returns a JSON payload that contains a wealth of information—not just the user’s IP address, but all the locational data that ipdata has about that address. For example: the ISP, city, state, country, continent, etc are provided in the payload. Because of this, you do not need to issue any other HTTP requests because you already have the information you need.

Sometimes, however, you do not need all the extraneous locational information, and ipdata’s API lets you filter the results by including the fields query parameter. For example:

The JSON payload contains only the fields specified by the fields query parameter. So, in this code, the resulting JavaScript object (named data ) has a single property called ip .

2. Using Cloudflare

ipdata’s web service is very easy to use. However, another (albeit limited) option is CloudFlare’s trace utility found at https://www.cloudflare.com/cdn-cgi/trace. It returns a plain-text set of key/value pairs, and the following shows a condensed example of the format:

As you can see, the output contains an ip key with its associated value, and you can parse it out with a regular expression like this:

This code defines a text() helper function that is similar to json() , but of course, it reads the response stream as text instead of a JSON structure.

Inside the callback function, you define a regular expression that matches an IPv4 address, and you use that regex to find a match within the response payload. The result gives you the user’s IP address that you can then use in your client-side code.

3. Using Amazon

A similar utility provided by AWS provides another reliable option to query your user’s IP address.

This will give you

Retrieving the Client’s IP in the Server (NodeJS)

IP stands for Internet Protocol, and it implements a type of networking called packet switching. It has the concept of hosts (machines), and it defines how data, in the form of packets, are sent between the hosts. In the case of HTTP, there are two hosts: client and server.

When a browser issues an HTTP request to a server, the request is transmitted from the client to the server in the form of IP packets. These packets contain a variety of information, but there are two particularly important things that every packet has: the source host address and the destination host address. Because every packet contains the client address, your server application can retrieve the client’s IP address from the packet.

Every framework, regardless of language and/or platform, has some mechanism for retrieving the client’s IP address. For Node.js applications, there are two such mechanisms:

  • the x-forwarded-for header.
  • the request.connection.remoteAddress property.

There is a slight issue, however; the x-forwarded-for header can contain multiple, comma-separated IP addresses. Thankfully, the first IP address in the x-forwarded-for header is typically the correct IP address. With that in mind, consider the following code:

A lot of this code is boilerplate, so let’s focus on the requestListener() function. The first line of the function retrieves the value of the x-forwarded-for header. It is not always guaranteed to be present. So, in the second line, you check if there is a value, and if so, you split it on a comma ( , ) and use the first item in the resulting array. If the x-forwarded-for header doesn’t exist, then you use req.connection.remoteAddress as a fallback.

Viola! You have the client’s IP address. It may not be 100% accurate (the end-user could be using a VPN to mask their true IP), but it is more reliable than getting the client’s address through the browser.

Customize Your Content with IPs

As you can see, using JavaScript to find an IP address is relatively simple, and it’s likely that you’ll want to do something with that address. Maybe you’ll want to show different promotions or ads to your users based upon their region, or you may need to convert currency on the fly. Regardless of your needs, ipdata’s web service provides comprehensive locational information based upon your user’s IP address. Go ahead and setup an account for free. It only takes a couple of minutes to get an API key, and you can use it experiment with the API to see what it can do for you.

GET VISITOR’S IP ADDRESS IN JAVASCRIPT

You must’ve noticed that all three sections which I have mentioned above require some kind of API or backend, this is because we cannot obtain IP address with just javascript in the browser, we need some server-side work however if you do not have experience on server-side you do not need to worry follow the first way where you will use ready-made API so you won’t have to write backend since it is already written by the ready-made API’s developers/owners.

CLIENT JS + READY-MADE APIs:

There are a lot of ready-made API services, but we will be using ipinfo.io,

WHY ARE WE USING IPINFO.IO?

We are using ipinfo.io because it allows us 50,000 Request per Month for free, which is a huge quota and I couldn’t find any other API having this huge limit for free. however, you can upgrade your plan according to your needs.

Creating an account on IPINFO.io is optional but preferred, you’ll get a token when you create an account, You can read IPINFO.IO’s Documentation for a deep understanding

CLIENT CODE SAMPLE:

you don’t need to read further, this is it you got the IP address and Geographical details of the IP, but if you need more limit than 50K request per month you’ll probably need to write and host your own API if that’s the case, you can follow the other 2 sections below

CLIENT JS + NodeJS:

Now in this method we will be using two technologies, Javascript on the browser and Javascript on the server (NodeJS), For this you need a hosting service where you can host your NodeJS server, However, this is not a hosting tutorial so I won’t go deep about hosting NodeJS, but I can suggest Heroku as it is the best free NodeJS host at the moment.

NODEJS CODE SAMPLE:

So here let me explain this code, We are using express to create a server in nodeJS this will allow us to listen to HTTPS requests, such as a GET request so that we can return IP address in response.

In NodeJS normally we get IP address using the request header x-forwarded-for as mentioned in code: req.headers[‘x-forwarded-for’] but the header name depends on your hosting configuration, such as if the IP address is coming from a remote address we will get the IP address using `req.connection.remoteAddress`
For example:

‘x-forwarded-for’ will not work on firebase cloud hosting it will return undefined or null, so we will use ‘ fastly-client-ip ‘ to get an IP address in firebase hosting, So the headers are dependent on which hosting you are using and It’s configuration that is why I have added all the headers and ways with OR operator so whatever the header works for your server will assign an IP address to the variable.
Now here we are also splitting ‘x-forwarded-for’ because on some hostings it returns more than one IP address separated with a comma.

GEO-IP DATA?

The above method returns just the IP address, No information about the country or location of IP address which may be required in some cases, Now we create another endpoint where we will return an object with IP and all related information, To get the country and other information of IP address we need a database having GEOGRAPHICAL IP ADDRESS details,

In-short we will use a third-party library to extract GEOGRAPHICAL data of the IP address, There are many libraries available but we will use GeoIP-Lite as this is the most downloaded library in this category.

NODEJS CODE SAMPLE WITH GEOIP

Here we created another endpoint name “IPwithData” and in response, we are sending the data received from third-party API “GeoIP-Lite” as it will look up into it’s database for details related to the IP address and returns all the details as an object.

Please note that the IP address is not found when you run this project locally on your machine, Nodejs will return “::1” as your IP address, but it will work perfectly when you host it on a Nodejs server like heroku.

Now we are done with the NodeJS/Serverside part of our “CLIENT JS+ NODEJS” section, let’s move toward the client-side code of this section

CLIENT SIDE CODE SAMPLE

client-side code of this section is almost the same compared to the code of the “CLIENTJS+ READY-MADE API” section.

Now here in this clientJS sample, the apiURL variable contains the URL of my Heroku server where I deployed the nodeJS code.

CLIENT JS + PHP

Now ClientJS+PHP is almost similar to NodeJS section, The only difference is that we write the backend code in PHP.

PHP CODE SAMPLE

Now this will return IP address string, but in-some cases you need Geographical data of IP address so we will use the same database that we used in NodeJS, MaxMind’s GeoIP-Lite2.

PHP CODE SAMPLE WITH GEOIP

Now our PHP API/Backend for IP address with GeoIP data is complete, let’s move forward to the client-side JS code to fetch these details on javascript.

CLIENT JS CODE SAMPLE

Wohooo!…

You’ve learnt all three ways of obtaining IP address in Javascript, If you’ve come this far and you believe that this blog helped you make sure to share the knowledge by sharing this blog.

WHAT IS AN IP ADDRESS?

An IP address can be compared to a Phone number, everyone has their phone number and it is a unique number so that you know where the call/message is coming from, Similarly, IP Address is completely unique to the computer or user it is assigned to. The creation of these numbers allows routers to identify where they are sending information on the internet.

WHY DO WE OBTAIN IP ADDRESS?

Well if you’re reading this page it means you already have a use-case but still, I will give you a few example,

  1. Google Analytics tool it uses IP address to differentiate unique visitors.
  2. Netflix uses the IP Address to detect the country of user and then display top trending movies of user’s country.
  3. you can use an IP address to block a user from your website,
  4. you can even block a whole country using the IP address,
  5. You can monitor your customer’s behavior and track your customers to increase your sales/orders and many more.

After reading these example, Now you know how powerful the IP address is.

Please note that some countries require user’s consent before obtaining any unique information from users, such as IP address so make sure to do some research on this.

WHAT IS CLIENT JS?

CLIENT JS full form Client-Side Javascript means the javascript that process on client-side in the browser

WHAT IS READY-MADE API?

READY-MADE APIs means a service/website that provides a ready-made endpoint, when a request is made to this endpoint you get the IP address in response

Читать:
Как сделать диск основным

Похожие статьи