Get ip client javascript

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.

Читайте также:  Содержание страницы код html

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:

function json(url) < return fetch(url).then(res =>res.json()); > let apiKey = 'your_api_key'; json(`https://api.ipdata.co?api-key=$`).then(data => < console.log(data.ip); console.log(data.city); console.log(data.country_code); // so many more properties >); 

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:

json(`https://api.ipdata.co?api-key=$&fields=ip`).then(data => < console.log(data.ip); >); 

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 .

Читайте также:  Разведочный анализ данных python пример

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:

h=www.cloudflare.com ip=178.25.55.75 ts=1605854122.426 visit_scheme=https uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36 

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:

function text(url) < return fetch(url).then(res =>res.text()); > text('https://www.cloudflare.com/cdn-cgi/trace').then(data => < let ipRegex = /3.4.3.4/ let ip = data.match(ipRegex)[0]; console.log(ip); >); 

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.

function getIPFromAmazon() < fetch("https://checkip.amazonaws.com/").then(res =>res.text()).then(data => console.log(data)) > getIPFromAmazon() 

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:

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:

const http = require('http'); function requestListener(req, res) < let forwarded = req.headers['x-forwarded-for'] let ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress; res.writeHead(200); res.end(ip); >const server = http.createServer(requestListener); server.listen(3000); console.log('Server listening at http://localhost:3000'); 

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.

Источник

How to get the client IP address with Javascript only

Carlos Delgado

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.

/** * Get the user IP throught the webkitRTCPeerConnection * @param onNewIP 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 = /(2(\.3)|[a-f0-9](:[a-f0-9]))/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 ?
https://api.ipify.org?format=jsonp jsonp callback(); ?
https://api.ipify.org?format=jsonp&callback=getip jsonp getip(); ?

You can use it with JSONP:

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.

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.

Источник

Read the User’s IP address in JavaScript

A MacBook with lines of code on its screen on a busy desk

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.

Script URL

Using with JavaScript

ajax = new XMLHttpRequest(); if(ajax!=null) < ajax.open("GET","https://europe-west3-devrcc.cloudfunctions.net/whatismyip",true); ajax.onreadystatechange = function() < if(this.readyState == 4) < if(this.status == 200) < console.log(this.responseText); >> > ajax.send(null); > 

Using with jQuery

$.getJSON('https://europe-west3-devrcc.cloudfunctions.net/whatismyip', function(data)< console.log(data); >)

Response

Get the location based on the IP

If you want to get the location based on the user’s IP address, you need to request a geo-location IP database, such as ipinfo.io. Services like this can give you a location in an API response like this one:

Источник

Оцените статью