Skip to content
the poor coder

javascript ip address

Poor Man
Published
Reading time
2 min read
On this page

Javascript IP Address#

If you want to get the IP address of the client using Javascript, there are few ways to do it.

Method 1: Using a third-party service#

One way to get the IP address is by using a third-party service like ipapi.co. This service provides a REST API that returns various information about the client, including their IP address.

Text
fetch('https://ipapi.co/json/')
  .then(response => response.json())
  .then(data => console.log(data.ip))

The above code fetches the JSON data from the https://ipapi.co/json/ URL and logs the client's IP address to the console.

Method 2: Using WebRTC#

Another way to get the IP address is by using WebRTC. WebRTC is a technology that enables real-time communication between browsers and mobile applications. It can also be used to get the client's IP address.

Text
const peerConnection = new RTCPeerConnection();
peerConnection.createDataChannel('');
peerConnection.createOffer()
  .then(offer => peerConnection.setLocalDescription(offer))
  .then(() => {
    const lines = peerConnection.localDescription.sdp.split('\n');
    const line = lines.find(l => l.startsWith('a=candidate'));
    const candidate = line.split(' ')[4];
    const [host, port] = candidate.split(':');
    console.log(host);
  });

The above code creates an RTCPeerConnection object and creates a dummy data channel to trigger ICE candidate gathering. It then creates an offer and sets it as the local description of the connection. Finally, it parses the SDP to extract the client's IP address.

Method 3: Using a server-side script#

One more way to get the IP address is by using a server-side script. You can make an Ajax request to a server-side script that returns the client's IP address.

Text
$.get('https://example.com/get-ip-address.php', function(data) {
  console.log(data);
});

The above code makes an Ajax request to the get-ip-address.php script on the example.com domain and logs the response to the console.

These are some of the ways you can get the IP address of the client using Javascript.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC