Getting external ip address linux

Check External IP using the Linux Command Line

Knowing the IP address of our computer is a basic task to establish network connections. But remember that there is also a public one with which we access the Internet, and doing it from the terminal can be an interesting task. Today, you will learn how to know the external IP address using the terminal.

In a typical network, the router uses a public IP address to identify it to the rest of the Internet. However, this same home router allows many devices to connect to this same router by assigning it another range of IP addresses that are known as private.

So, the device has a private IP address to communicate with the internal network, but the router uses a different one to access the Internet. Here is the difference between the private IP and the public IP.

To know the private IP from the terminal, it would be enough to use the ipconfig command. But in the case of the external or public IP, the process is a little different.

I will show you several ways to do it.

Check External IP using the Linux Command Line

The reality is that there are many commands and ways to do this process. The first way to do this is by using the dig command.

In this case, the dig command will make a request to a website that will provide us with the external or public IP address.

dig +short myip.opendns.com @resolver1.opendns.com 

The output on the screen will simply be, the IP address you are looking for. For example:

Источник

Linux command for public ip address

and many more. But they all are giving me internal IP Address. Then I found some sites which provides API for this. Example : curl http://ipecho.net/plain; echo But I don’t want to rely on third party website service. So, is there any command line tool available to get external IP Address?

12 Answers 12

You can use this command to get public ip and private ip(second line is private ip; third line is public ip.)

Читайте также:  Kali linux установка русского языка

It’s the cleanest solution, it’s sad that most of articles / answers using external resources to get IP instead of this simple solution

simplest of all would be to do : curl ifconfig.me

Yes, it works fine as I have mentioned in my question, But I do not want to depend on this third party service. What if that server stop this service in future?

You could use this script

# !/bin/bash # echo 'Your external IP is: ' curl -4 icanhazip.com 

But that is relying on a third party albeit a reliable one. I don’t know if you can get your external IP without asking someone/somesite i.e. some third party for it, but what do I know.

This is doing the same thing as a command the -4 is to get the output in Ipv4

I would suggest you to use the command external-ip ( sudo apt-get install miniupnpc ) as it (I’m almost sure) uses upnp protocol to ask the router instead of asking an external website so it should be faster, but of course the router has to have upnp enabled.

It might not work on amazon because you might be using NAT or something for the server to access the rest of the world (and for you to ssh into it also). If you are unable to ssh into the ip that is listed in ifconfig then you are either in a different network or dont have ssh enabled.

ifconfig eth0 | awk '/inet / < print $2 >' | sed 's/addr://' 

That returns whatever is IP address assigned to your eth0 device. So if your server is hosted on Amazon, and was assigned an internal IP address, and since Amazon instances are using NAT, that’s what you’d see. If you want a sure reliable way of getting your external, public IP address, then use one of the external service like ifconfig.me.

This is the best I can do (only relies on my ISP):

ISP=`traceroute -M 2 -m 2 -n -q 1 8.8.8.8 | grep -m 1 -Eo '8\.3\.3\.8'` extIP=`ping -R -c 1 -t 1 -s 1 -n $ISP | grep RR | grep -m 1 -Eo '9\.1\.9\.3'` echo $extIP 

Or, the functionally same thing on one line:

ISP=`traceroute -M 2 -m 2 -n -q 1 8.8.8.8 | grep -m 1 -Eo '9\.2\.4\.2'` | ping -R -c 1 -t 1 -s 1 -n $ISP | grep RR | grep -m 1 -Eo '7\.4\.8\.3' 

to save it to a temporary & hidden file add > .extIP to the end of the last line, then cat .extIP to see it.

Читайте также:  Сетевое администрирование linux iptables

If your ISP’s address never changes (honestly i’m not sure if it would or not), then you could fetch it once, and then replace $ISP in line two with it

This has been tested on a mac with wonderful success. the only adjustment on linux that I’ve found so far is the traceroute «-M» flag might need to be «-f» instead and it relies heavily on the ping’s «-R» flag, which tells it to send back the «Record Route» information, which isn’t always supported by the host. But it’s worth a try!

the only other way to do this without relying on any external servers is to get it from curl’ing your modem’s status page. I’ve done this successfully with our frontier DSL modem, but it’s dirty, slow, unreliable, and requires hard-coding your modem’s password. Here’s the «process» for that:

curl http://[user]:[password]@[modem's LAN address]/[status.html] | grep 'WanIPAddress =' | grep -m 1 -Eo '4\.1\.6\.2' 

That fetches the raw html, searches for any lines containing «WanIpAddress mt24″>

Источник

Check External IP From Linux Command Line

There are a few different ways to check a system’s external IP address from the Linux command line. Check out some of the methods below to retrieve your public IP address using Linux commands.

Using dig, curl, and wget commands to check external IP address in Linux

Retrieve External IP Address in Command Line

Method 1. Use the dig command to see your IP address from different name servers, such as opendns.com or Google’s name server.

$ dig +short myip.opendns.com @resolver1.opendns.com

Or with Google’s name server:

$ dig TXT +short o-o.myaddr.l.google.com @ns1.google.com

Method 2. We can also use the curl command and third party websites to view our external IP address. icanhazip.com will show both the IPv4 and IPv6 addresses.

Method 3. We can also use the wget command and third party websites to view the external IP address. Once again, we will use icanhazip.com to show both the IPv4 and IPv6 addresses.

Читайте также:  Удалить debian gnu linux

Method 4. There are a bunch of other websites that can be used to view your external IP address. Here’s a few of them that you can try. If you have any more to contibute, or want to report one that no longer works, feel free to leave a comment below.

$ curl ifconfig.me $ wget -qO - ifconfig.me
$ curl api.ipify.org $ wget -qO - api.ipify.org
$ curl ipecho.net/plain $ wget -qO - ipecho.net/plain
$ curl ipinfo.io/ip $ wget -qO - ipinfo.io/ip

Источник

Как узнать внешний ip из консоли

Внешний ip

Доброго дня дорогие читатели. Сегодня хочу затронуть тему о том как узнать внешний ip из консоли.

Есть много других вариантов как узнать свой внешний ip адрес, например, открыть браузер и зайти на сайт. Определяющий ваш внешний ip адрес сайтов достаточно много, найти их не составит труда. Но есть определенные моменты когда браузера нет в системе. Например, есть у вас Asterisk только с консольным доступом. Для настройки sip провайдера и привязки его к внешнему ip нужно его указать. Сеть в организации может быть большая и точно определить внешний ip адрес возможно лишь с сервера Asterisk.

Можно привести и другой пример, сервер Windows Core или бесплатный Hyper-V, там тоже изначально только консоль. Давайте уже узнаем наш внешний ip адрес

Узнать внешний ip адрес из консоли Linux

Данный метод работоспособен для Ubuntu, Centos, Gentoo и прочих дистрибутивов

На случай если указанный выше сайт перестанет работать ниже приведу еще несколько рабочих вариантов

wget -qO- ipecho.net/plain curl ifconfig.me wget -O - -q ifconfig.me/ip
Узнать внешний ip адрес из консоли Windows
Nslookup

Определить ваш внешний адрес из консоли 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")

Источник

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