Get your public IP address - very fast!

Overview

public-ip

Get your public IP address - very fast!

In Node.js, it queries the DNS records of OpenDNS, Google DNS, and HTTPS services to determine your IP address. In browsers, it uses the excellent icanhaz and ipify services through HTTPS.

Install

$ npm install public-ip

Usage

const publicIp = require('public-ip');

(async () => {
	console.log(await publicIp.v4());
	//=> '46.5.21.123'

	console.log(await publicIp.v6());
	//=> 'fe80::200:f8ff:fe21:67cf'
})();

API

publicIp.v4(options?)

publicIp.v6(options?)

Returns a Promise<string> with your public IPv4 or IPv6 address. Rejects on error or timeout. A .cancel() method is available on the promise, which can be used to cancel the request.

options

Type: object

onlyHttps

Type: boolean
Default: false

Use a HTTPS check using the icanhazip.com service instead of the DNS query. ipify.org is used as a fallback if icanhazip.com fails. This check is much more secure and tamper-proof, but also a lot slower. This option is only available in the Node.js version. The default behaviour is to check against DNS before using HTTPS fallback. If set to true, it will only check against HTTPS.

fallbackUrls

Type: string[]
Default: []

Add your own custom HTTPS endpoints to get the public IP from. They will only be used if everything else fails. Any service used as fallback must return the IP as a plain string.

const publicIp = require('public-ip');

(async () => {
	await publicIp.v6({
		fallbackUrls: [
			'https://ifconfig.co/ip'
		]
	});
})();
timeout

Type: number
Default: 5000

The time in milliseconds until a request is considered timed out.

Maintainers

Related

Comments
  • Add method to get either IPv6 or IPv4

    Add method to get either IPv6 or IPv4

    Currently, in the browser version if v6 function is called and the API request returns a v4 version, then an error is made and we can't get the IP.

    It'd be good if there's a single function to return IPV6/IPV4, if v6 is available :

    console.log(await publicIp.get());
    //=> '46.5.21.123' or v6 if available (preferred)
    
    bug help wanted 
    opened by subins2000 14
  • Add new API URLs

    Add new API URLs

    Fixes #45 Added new general HTTPs APIs from which IP is retrieved with a regex pattern. Adds a JSON object to do that :

    general: {
      'https://www.cloudflare.com/cdn-cgi/trace': 'ip(=)(.*?)\n',
      'https://ip-api.io/api/json': 'ip"(.*?)"(.*?)"'
    }
    
    opened by subins2000 13
  • Add redundancy, remove `https` option, add `onlyHttps` option…

    Add redundancy, remove `https` option, add `onlyHttps` option…

    Some things that could be considered to be useful:

    • Multiple DNS resolver host alternatives
    • Multiple DNS resolver providers
    • Fallback to HTTPS by default if DNS does not resolve (no need to choose one or the other, just try DNS and if it fails use HTTPS)
    • Ability to disable or enable HTTPS check ({ https: true } will only check HTTPS). Defaults to DNS + HTTPS
    • Added options.urls array to be able to add more urls to fallback to (like ifconfig.co)
    opened by ghostnumber7 12
  • rewrite to use `dns-socket` module instead of `native-dns`

    rewrite to use `dns-socket` module instead of `native-dns`

    might fix #5

    @galambalazs Could you try this out? I couldn't test as my current connection is blocking it somehow.

    @silverwind This was easier to implement with and support retries so it's more resilient.

    opened by sindresorhus 11
  • Add more public IP checks for better resilience

    Add more public IP checks for better resilience

    Issuehunt badges

    See https://github.com/sindresorhus/is-online/issues/64. One or two alternative services to be checked in parallel would probably be beneficial for better resilience against outages.


    IssueHunt Summary

    adityapatadia adityapatadia has been rewarded.

    Backers (Total: $40.00)

    Submitted pull Requests


    Tips


    IssueHunt has been backed by the following sponsors. Become a sponsor

    enhancement help wanted :gift: Rewarded on Issuehunt 
    opened by silverwind 10
  • cluster error: [Error: Request timed out]

    cluster error: [Error: Request timed out]

    When starting a fleet of instances (e.g. -i 4) with pm2, and public-ip runs inside each instance upon launch, only the first one succeeds. All the other ones report this error:

    [Error: Request timed out]

    Example script:

    require('public-ip').v4(function (err, ip) {
        if (err) return console.error('no public IP found', err);
        console.log('ip', ip)
    });
    

    pm2 start publicIp.js -i 4

    bug help wanted 
    opened by gblazex 10
  • Add support for IPv6

    Add support for IPv6

    Hello,

    Since we're reaching the end of IPv4 blocks, it seems like a good idea to support IPv6. This modification seems to do the job, but before continuing I wanted to get your feedback on the direction it's taking since it's obviously a breaking change. Of course you'll need an IPv6 ready network to make the tests pass.

    opened by Marsup 9
  • Fix problem with calling the browser version concurrently

    Fix problem with calling the browser version concurrently

    • Uses closure on xhr to avoid referencing the wrong xhr object in the load callback if multiple requests are done in parallel
    • Remove the abort method that was not exported so was useless

    Closes #52

    opened by stropitek 8
  • Support for zscaler

    Support for zscaler

    some organizations use zscaler. This causes some ip resolver services to recognize the zscaler IP instead of the actual user's IP.

    This issues is to request the support of overriding the standard ip address resolvers (icanhazip and ipify) with a list of user defined resolvers.

    opened by jgroom33 6
  • IP v6 is not working, ipv6.icanhazip service is down

    IP v6 is not working, ipv6.icanhazip service is down

    Cannot get IP v6, the service https://ipv6.icanhazip.com/ seems down, or maybe it was moved, anyhow this library is not working for v6 anymore following the examples. The browser displays this error: ipv6.icanhazip.com’s server IP address could not be found. Maybe the service maintainers deleted the DNS for the "ipv6" subdomain.

    IP v4 does work.

    Testing code:

    const publicIp = require('public-ip');
    (async () => {
    	console.log(await publicIp.v6());
    })();
    

    public-ip version: 3.2.0 I submited the issue to major/icanhaz here.

    opened by LazaroOnline 6
  • Getting `Query timed out` on AWS EC2 instance

    Getting `Query timed out` on AWS EC2 instance

    We are using AWS EC2 instance and have implemented node.js server written in hapi js which is deployed using docker. On our development server public-ip library is giving proper result. Now we have setup staging server with similar configuration. Here we are getting below error.

    error:  Error: Query timed out
        at DNS._ontimeout (/usr/src/app/node_modules/public-ip/node_modules/dns-socket/index.js:98:18)
        at ontimeout (/usr/src/app/node_modules/public-ip/node_modules/dns-socket/index.js:52:10)
        at wrapper (timers.js:275:11)
        at Timer.listOnTimeout (timers.js:92:15)
    

    Can you please suggest some way out of this issue? Let me know if any further information required.

    opened by gauravc-cuelogic 6
  • timeout options doesn't work as expected

    timeout options doesn't work as expected

    I tried this line without internet access and after approximately 9 seconds later it return error "Error: Couldn't find your IP" publicIp.v4({timeout:100}).then(value => console.log(value)).catch(err => console.log(err));

    I was expecting it to error out within 100 milliseconds, not 9000 milliseconds. Am I missing something?

    bug help wanted 
    opened by akeonly 2
Releases(v6.0.1)
  • v6.0.1(Jun 24, 2022)

  • v6.0.0(Jun 13, 2022)

    Breaking

    • Use named exports instead of methods on a default export (#63) 4e1d895
      • import publicIp from 'public-ip'; publicIp.v6();import {publicIpv6} from 'public-ip'; publicIpv6();
    • Allow getting either IPv6 or IPv4 (#63) 4e1d895

    https://github.com/sindresorhus/public-ip/compare/v5.0.0...v6.0.0

    Source code(tar.gz)
    Source code(zip)
  • v5.0.0(Dec 27, 2021)

    Breaking

    • Require Node.js 14 e53d7fe
    • This package is now pure ESM. Please read this.

    Improvements

    • Throw a special error subclass when the public IP address could not be found d353d7c

    https://github.com/sindresorhus/public-ip/compare/v4.0.4...v5.0.0

    Source code(tar.gz)
    Source code(zip)
  • v4.0.4(May 29, 2021)

  • v4.0.3(Dec 7, 2020)

    • Fix problem with calling the browser version concurrently (#53) f0a7f07

    https://github.com/sindresorhus/public-ip/compare/v4.0.2...v4.0.3

    Source code(tar.gz)
    Source code(zip)
  • v4.0.2(Jul 10, 2020)

  • v4.0.1(Mar 30, 2020)

  • v4.0.0(Nov 22, 2019)

    Breaking

    • Rename the http option to onlyHttps. Previously, the default behavior was to use DNS, and if that failed, the request would fail. What's changed is that by default it will now try DNS, and if that fails, it will fall back to HTTPS. The option was renamed to better reflect that HTTPS is used even when {onlyHttps: false}.

    Enhancements

    • Add built-in fallbacks for DNS and HTTP checks (#34) fdcbb7d
    • Add fallbackUrls option to enable users to add additional HTTP fallbacks (#34) fdcbb7d

    https://github.com/sindresorhus/public-ip/compare/v3.2.0...v4.0.0

    Source code(tar.gz)
    Source code(zip)
  • v3.2.0(Aug 14, 2019)

  • v3.1.0(Apr 24, 2019)

  • v3.0.0(Dec 14, 2018)

Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Get current wifi password

wifi-password Get current wifi password Install $ npm install wifi-password Usage const wifiPassword = require('wifi-password'); wifiPassword().then

Kevin Mårtensson 591 Dec 17, 2022
Get the current local time of a GitHub user.

dev-time-cli Get the current local time of a GitHub user. Install $ npm install --global dev-time-cli Usage $ dev-time --help Usage $ dev-time

Sam Verschueren 176 Jun 29, 2022
Reliably get the terminal window size

term-size Reliably get the terminal window size Because process.stdout.columns doesn't exist when run non-interactively, for example, in a child proce

Sindre Sorhus 132 Oct 11, 2022
NodeJS built CLI, allows to spell check in 14 languages, get Coleman-Liau Index and build hash Pyramids

Magic CLI ?? ?? NodeJS built CLI, allows to spell check in 14 languages, get Coleman-Liau Index and build hash Pyramids Installing Install dependencie

Lucas 3 Sep 27, 2022
A project for FAST command line interface tools.

FAST CLI Project This is the FAST CLI project, containing the FAST CLI package and other related CLI packages for FAST project creation and management

Microsoft 24 Dec 5, 2022
Find and fix problems in your JavaScript code.

ESLint Website | Configuring | Rules | Contributing | Reporting Bugs | Code of Conduct | Twitter | Mailing List | Chat Room ESLint is a tool for ident

ESLint 22k Jan 8, 2023
Test your internet connection speed and ping using speedtest.net from the CLI

speed-test Test your internet connection speed and ping using speedtest.net from the CLI Install Ensure you have Node.js version 8+ installed. Then ru

Sindre Sorhus 3.8k Jan 7, 2023
:eyeglasses: Node.js module that tells you when your package npm dependencies are out of date.

Node.js module that tells you when your package npm dependencies are out of date. Getting Started Install Node.js. Install david: cd /your/project/dir

Alan Shaw 953 Dec 25, 2022
Translations with speech synthesis in your terminal as a node package

Normit Normit is an easy way to translate stuff in your terminal. You can check out its Ruby gem version termit. Installation npm install normit -g Us

Paweł Urbanek 234 Jan 1, 2023
:sparkles: Make your JSON look AWESOME

Make your JSON objects look AWESOME! This package allows you to give style to your JSON on your console! Installation : $ npm install jsome if you n

Khalid REHIOUI 234 Dec 3, 2022
Terminal recorder: Record your termial session into HTML

terminal-recorder Terminal recorder allows you to record your bash session, and export it to html so then you can share it with your friends. GitHub P

Cristian Cortez 104 Mar 3, 2022
📜 Create mutable log lines into the terminal, and give life to your logs!

Because Logging can be pretty and fun Installation $ npm install draftlog What it does It allows you to re-write a line of your log after being writt

Ivan Seidel 1.2k Dec 31, 2022
Simple config handling for your app or module

conf Simple config handling for your app or module All you have to care about is what to persist. This module will handle all the dull details like wh

Sindre Sorhus 1k Jan 7, 2023
An extension geared towards Spotify users with larger libraries; view all your playlists that contain a specific song with the click of a button. Designed for Spicetify (https://github.com/khanhas/spicetify-cli)

ViewPlaylistsWithSong An extension developed for Spicetify that allows you to view all the playlists in your library that contain a certain song. Idea

null 21 Dec 13, 2022
HMSC (How Much Stuffs CLI) analyst for your files and folders

HMSC ?? About HMSC (How Much Stuffs CLI) analyst for your files and folders ?? Screenshot ?? Requirements Node.js NPM ?? Installation $ npm i -g hmsc

Abdullah Veliyev 26 Jan 10, 2022
Add a hungry turtle to your terminal and feed it every time you mistype 'npm' as 'nom'

Nom Does this ever happen to you? You happily code away on a project, navigating the command line like a pro, testing, error logging, installing packa

Meike Hankewicz 5 Apr 26, 2022
Google Chrome extension which randomly generates a customisable 3D bamboo forest in your new tab

Bamboo-New-Tab bamboo-new-tab-demo.mp4 bamboo-new-tab-options-demo.mp4 Try it out Hosted version: https://conwayjw97.github.io/Bamboo-New-Tab/ To run

James 15 Nov 16, 2021
A C++ based command-line (CLI) program that lets you manage your tasks

COMMAND LINE INTERFACE TODO APP a command-line (CLI) program that lets you manage your tasks. The specification for this project is written down as te

Rahul Prabhakar 1 Dec 25, 2021
1History is a command line tool to backup your histories of different browsers into one place

1History All your history in one place. 1History is a command line tool to backup your histories of different browsers into one place. Features Suppor

null 340 Dec 31, 2022