NOTE: This is about external IP address (the one that the servers on the Internet see when you connect to them) — if you want internal IP address (the one that your own computer is using for connections, which may be different) see this answer.
For finding the external ip, you can either use external web-based services, or use system based methods. The easier one is to use the external service, also the ifconfig based solutions will work in your system only if you’re not behind a NAT. the two methods has been discussed below in detail.
- TL;DR — Fastest methods in 2015
- The fastest using HTTP
- The fastest using HTTPS with a valid cert
- Using telnet
- Using FTP
- DNS
- Finding external IP using external services
- Now a long story.
- Finding external IP without relying on external services
- Comments
- Domain names
- A faster (arguably the fastest) method using dig with OpenDNS as resolver
TL;DR — Fastest methods in 2015
or using externalip:
The fastest using HTTP
curl -s http://whatismyip.akamai.com/
The fastest using HTTPS with a valid cert
curl -s https://4.ifcfg.me/
Using telnet
With nc command:
With telnet command:
Using FTP
externalip dns
externalip http
externalip https
externalip telnet
externalip ftp
You mean whatever routable IP your dsl/cable modem/etc. router has?
wget http://checkip.dyndns.org -O —
You should get something like
I’ve changed the IP in mine to a generic non-routable and bolded it for you.
Which will give you just
Доброго дня дорогие читатели. Сегодня хочу затронуть тему о том как узнать внешний ip из консоли.
Есть много других вариантов как узнать свой внешний ip адрес, например, открыть браузер и зайти на сайт. Определяющий ваш внешний ip адрес сайтов достаточно много, найти их не составит труда. Но есть определенные моменты когда браузера нет в системе. Например, есть у вас Asterisk только с консольным доступом. Для настройки sip провайдера и привязки его к внешнему ip нужно его указать. Сеть в организации может быть большая и точно определить внешний ip адрес возможно лишь с сервера Asterisk.
Можно привести и другой пример, сервер Windows Core или бесплатный Hyper-V, там тоже изначально только консоль. Давайте уже узнаем наш внешний ip адрес
Узнать внешний ip адрес из консоли Linux
Данный метод работоспособен для Ubuntu, Centos, Gentoo и прочих дистрибутивов
wget -qO- eth0.me
На случай если указанный выше сайт перестанет работать ниже приведу еще несколько рабочих вариантов
Узнать внешний ip адрес из консоли Windows
Определить ваш внешний адрес из консоли WIndows можно с помощью утилиты nslookup. Обычно nslookup используется для проверки работы DNS. Есть один хитрый способ, как с помощью данной утилиты узнать свой внешний ip адрес. Выполним следующую команду:
nslookup myip.opendns.com. resolver1.opendns.com
Мы выполнили запрос к серверу DNS под названием resolver1.opendns.com. Он в свою очередь должен был выдать нам ip адрес доменного имени myip.opendns.com. Но весь смысл в том, что DNS сервер resolver1.opendns.com настроен так, чтобы при запросе конкретного домена выдавать ip адрес с которого поступил запрос. Вот так без особых усилий мы узнали наш внешний ip.
Powershell
Можно использовать и Powershell. Будет удобно для дальнейшей работы с ip в ваших скриптах.
$ip = new-object System.Net.WebClient
$ip.DownloadString(«http://ipinfo.io/ip»)
Хотите отблагодарить автора статьи? Это даст ему дополнительный стимул к написанию новых статей.
This is the source of my externalip-benchmark script that I used:
You can run it yourself to see which services mentioned here are worth using:
My results that I got on 2015-04-03 from Warsaw — the addresses have been changed to protect the innocent:
Best http response times:
Best https response times:
(Note: there are some fast responses with empty content — those are invalid.)
Best average ping times:
Here are the results that I got on 2015-04-03 from Amsterdam:
(The 999999 pings mean 100% packet loss.)
DNS
For a comparison here are times that other methods take — tested on 2015-06-16 from Warsaw and Amsterdam.
usually takes (real wall clock time) about:
- 0.035s from Warsaw
- 0.015s from Amsterdam
There are actually four resolvers that can be used this way:
- resolver1.opendns.com
- resolver2.opendns.com
- resolver3.opendns.com
- resolver4.opendns.com
They all give the same response times in Warsaw and Amsterdam but this may not be the case in other locations.
Using 208.67.222.222 — the IP of resolver1.opendns.com instead of its domain name is faster:
- 0.023s from Warsaw
- 0.009s from Amsterdam
but may not work in the future if the IP ever changes (though it may be unlikely for a well known DNS resolver — maybe I should use the IP in my externalip script — please comment).
Telnet with nc or telnet command (see above) usually takes:
- 0.103s from Warsaw
- 0.035s from Amsterdam
(There is no noticeable difference between nc and telnet commands.)
- 0.104s from Warsaw
- 0.036s from Amsterdam
Finding external IP using external services
The easiest way is to use an external service via a commandline browser or download tool. Since wget is available by default in Ubuntu, we can use that.
To find your ip, use-
You could also use lynx(browser) or curl in place of wget with minor variations to the above command, to find your external ip.
Using curl to find the ip:
For a better formatted output use:
Now a long story.
There are a lot of options of different servers providing the external IP especially via HTTP posted here or elsewhere.
I made a benchmark to see if any of them are better than the others and I was surprised by the results. E.g. one of the most widely recommended ifconfig.me was almost always the slowest for me, sometimes taking many seconds to respond. Many don’t work over HTTPS, or do work but have invalid certificates. Some have very inconsistent response times.
Finding external IP without relying on external services
N.B: Outputs are indicative and not real.
Comments
If you see some interesting results from your location, or if you think that some other hosts should be recommended instead of those that I’ve chosen, please post a comment. If there is any important service missing, please comment or post an issue on GitHub. I’d like to keep this post updated with a current choice of best-performing services.
Domain names
All of the methods will be faster (especially when run for the first time) when IP addresses will be used instead of the domain names of the given services (except with HTTP that can use host-based virtual servers and not work with bare IP — not tested) but will stop working when the services change the IP address so it may be faster but less future-proof.
A faster (arguably the fastest) method using dig with OpenDNS as resolver
- The DNS response protocol is standardised (the format will stay compatible).
- Historically DNS services (OpenDNS, Google Public DNS, ..) tend to survive much longer and are more stable, scalable and generally looked
after than whatever new hip whatismyip.com HTTP service is hot today.
Using dig with OpenDNS as resolver:
Copied from: https://unix.stackexchange.com/a/81699/14497