- How To Find My Public IP Address From Command Line On a Linux
- Explain IP addresses
- Use dig command for determining my public IP address:
- How to Find IP Address in Linux Command Line
- Find IP address in Linux command line
- Other ways to find the IP address of your system in Linux
- Show IP address with hostname command
- Display IP address with nmcli tool
- What about ifconfig?
- Bonus Tip: Finding the public IP address of your system
- How to Find Your IP Address in Linux
- Four ways to find your current IP Address in Linux
- Method # 1: On the Desktop
- Method #2: On the Shell with ip command
- Method # 3: On the Shell with ifconfig command
- Method # 4: On the Shell by using hostname command
- Conclusion
- Karim Buzdar
- Как в линуксе узнать IP-адрес
- IP-address — что это?
- Внутренний IP-адрес в Линукс
- Локальный IP-адрес в Линукс
- Как узнать Внешний IP-адрес
- Заключение
How To Find My Public IP Address From Command Line On a Linux
H ow do I find out my public IP address on the Linux and OS X Unix command line to use with my own bash shell script without using third party web site? Is there command-line option which will show my dynamic IP address on a Ubuntu or Fedora Linux?
There are many ways to find out your public IP address or wan (Wide Area Network) IP on a Linux or Unix-like operating systems such as FreeBSD, OpenBSD, NetBSD, Apple OS X, and others.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Linux, macOS, WSL or Unix-like OS |
Est. reading time | 2 mintues |
This page explain how to find out your own IP address using command line options on an Ubuntu, Debian, CentOS Linux, macOS/OS X and Unix bash shell.
Explain IP addresses
An IP is short for Internet Protocol. It is used to identify computers or mobile devices on the Internet. Each device connected to the Internet has an IP address. IP address can be used to personalize information.
Use dig command for determining my public IP address:
- Open the Terminal application on Linux or Unix.
- Type the following dig (domain information groper) command on a Linux, OS X, or Unix-like operating systems to see your own public IP address assigned by the ISP:
dig +short myip.opendns.com @resolver1.opendns.com - You can also type:
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com - You should see your IP address on screen. This is the fastest way to find out your IP address without using 3rd party site.
Fig.01: Use dig command to find your IP address
Источник
How to Find IP Address in Linux Command Line
A Few years back, ifconfig was the favorite way to know IP address in Linux. Unfortunately, ifconfig command has been deprecated. If you try to use this command today, you are most likely to see the following error:
So, how do you find the IP address then? Let me show you how to do that.
Find IP address in Linux command line
Well, you can use the ip command for this purpose. ip command is versatile and can be used for several other things related to networking.
But just to show the IP address, use the command with ip addr, ip a or ip address options (all are same) in the following manner:
And you will see an output like this:
In the above output, you can ignore the first one called lo (loopback). You can see that the IP address is displayed 192.168.1.20. The 24 that follows it is the subnet mask.
That’s it. That’s how you display IP address of host system in Linux command line.
Other ways to find the IP address of your system in Linux
There are more ways to check the IP address in Linux. Let me show you them as well.
Show IP address with hostname command
The hostname command usually displays the hostname of your system. It can also be used to display the IP address of the host:
It will simply display the IP address of the host in the terminal.
Display IP address with nmcli tool
Most Linux distributions come with a Network Manager tool. This tool has a command line interface called nmcli. You can use this nmcli tool to view a number of network configurations.
The IP address can be displayed with:
You should see the IP address in the output.
What about ifconfig?
Actually, you can still use ifconfig command. It is present in net-tools package. You can install it using the package manager of your system. However, use of net-tools is not encouraged so I suggest sticking with the ip command.
In Ubuntu-based distributions, you can install net-tools using this command:
Now you can use the ifconfig command to display the IP address of your system.
The output will be like this:
Again, ifconfig has been deprecated and should not be used.
Bonus Tip: Finding the public IP address of your system
What you saw so far was to display the private IP address of your system. What I mean is that if you use a network router, you are most probably behind a NAT.
The IP address of your system is a private one, used only for communicating with the devices on your sub-network. Any device outside your home/work network won’t be able to find you with this IP address. They need to now the IP address of your router. Your router recognizes your device and communicates via the private IP address.
How do you get your public IP address (IP address of your router)? You’ll have to utilize third party tools.
For example, you can use the host command with OpenDNS and get the public IP address:
The output should be similar to this:
In the end…
I hope this quick tip helped you in finding the IP address of your system in Linux command line. You may also read about finding the gateway IP in Linux.
As always, feel free to provide your feedback and suggestion in the comment section below.
Источник
How to Find Your IP Address in Linux
Many times it happens that you feel the need of knowing the IP address of your device. Internet Protocol address or IP address is a set of numeric digits that are needed to identify your device and enable network communication because all the devices that are connected through a network know each other only through their IP addresses. Moreover, the IP address also specifies the location of a device. So it becomes necessary for you at times to know what is the IP address of whichever device you are using. Now how to find this IP address is the real question. In the article below, we will tell you all the ways through which you can find the IP address of your device while working in Linux environment, in our case Ubuntu 18.04.
Four ways to find your current IP Address in Linux
Following are the four methods through which you can find the IP address of your device:
Method # 1: On the Desktop
The first method of finding the IP address of your device is through the Linux desktop interface. For this, you need to proceed as follows:
Click on your network connection icon (Wi-Fi icon) shown at the top right of the title bar on which Ubuntu Desktop is written. A cascading menu will appear which is shown below:
From the menu shown above, click on Connection Information. A new Connection Information window will appear which is shown below:
In the window shown above, the red highlighted rectangle shows the IP address of your device written in front of IP Address field.
Method #2: On the Shell with ip command
The second method of finding the IP address of your device is through a terminal command. In order to do this, you need to perform the following steps:
First of all, open terminal by pressing Ctrl+ T or you can click on the terminal icon directly if it is shown on your task bar. You can also click on the search icon located on the taskbar and then type Terminal and press enter to open it. The newly opened terminal window is shown below:
Type the command ip addr show in the terminal and press enter.
This command is shown below: Advertisement
As soon as you will press enter, some information will be displayed on the terminal window. From the information shown below in the terminal screen, the highlighted rectangle shows the IP address of your device beside the inet field.
Method # 3: On the Shell with ifconfig command
The third method of finding the IP address of your device is through another terminal command. For this you need to follow the steps mentioned below:
Launch terminal by pressing Ctrl+ T or clicking on the terminal icon or searching for terminal in the search window shown below and pressing enter.
Then type the command:
in the newly opened terminal window and press enter.
As soon as you will press enter, a lot of information will be displayed on the terminal screen. From the displayed information below, the highlighted rectangle shows the IP address of your device besides the field of inet addr.
The ifconfig command works in the same way for finding the IP address of a device using terminal in Linux as ipconfig command works for finding the IP address of a device using command prompt in Windows.
Method # 4: On the Shell by using hostname command
The method four for finding the IP address of your device makes use of yet another terminal command. For this method, you need to follow the following steps:
Launch terminal by pressing Ctrl+ T or clicking on the terminal icon located on the taskbar or search for terminal in the search window and press enter.
When the terminal window will appear, type the command:
and press enter. This command is shown in the following window:
As soon as you will press enter, the IP address of your device will be displayed on the terminal right below your entered command. This is shown below:
Conclusion
By making use of any of the methods listed above, you can find the IP address of your device very easily and enable a very safe and secure network communication through it. IP address gives an identity to your device so that you can recognize it whenever you want to. Once you know the IP address of your device, you are free to interact with any other device that is connected to the same network to which you are connected. I hope that this article will help you a lot in future.
Karim Buzdar
About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn
Источник
Как в линуксе узнать IP-адрес
IP-адрес устройства служит неким идентификатором в локальной сети Интернет. К каждому ПК привязан собственный адрес, при помощи которого распознается устройство. Во многих ситуациях пользователь может обойтись и без этой информации, однако, в некоторых случаях знать IP Linux всё же полезно. Эти данные могут понадобиться для работы с домашним компьютером, а также с локальной сетью.
В данной статье будут рассмотрены альтернативные способы того, как узнать IP-адрес устройства Linux.
IP-address — что это?
IP-адреса принято делить на 3 типа:
- IP-адрес ПК (внутренний адрес);
- Адрес в локальной сети;
- Внешний IP-адрес.
Программное обеспечение любого устройства функционирует между собой при помощи сетевых протоколов. Для нормального взаимодействия нескольких программ требуется внутренний IP ПК. Обычно этот адрес выглядит следующим образом:
Если говорить об адресах локальной сети, то в этом вопросе возникают определенные трудности. По идее, каждый компьютер должен иметь уникальный сетевой идентификатор, но с некоторых пор это стало невозможным. В мире появилось слишком много устройств – свободные адреса начали стремительно заканчиваться. Теперь обычный пользователь не может иметь ПК с собственным IP-адресом в локальной сети (эта возможность доступна только серверам). Через NAT провайдеры начали размещать своих клиентов на одинаковых IP.
Это приводит к тому, что компьютер без проблем получает доступ к Интернет-серверу, но подключиться к такому ПК невозможно, поскольку его адрес совпадает с адресом сотни других устройств. Их владельцы также получили его от провайдера.
На текущий момент времени не существует иного способа осуществить подключение устройства к Интернету. Без NAT пользователю пришлось бы обеспечить отдельное Интернет-подключение для каждого устройства (например, для двух ноутбуков). А это, как минимум, очень дорого и неудобно.
Резюмируем: благодаря NAT подключение устройства к локальной сети происходит за счет получение устройством внешнего IP, принадлежащего поставщику услуг (провайдеру). Этот адрес также используется сотнями других пользователей.
Внутренний IP-адрес в Линукс
Следует еще раз напомнить о том, что внутренний адрес устройства всегда идентичный. Он был упомянут выше. Данная информация актуальна не только для пользователей Linux, но и остальных операционных систем. Если хочется убедиться в правдивости информации, можно воспользоваться терминалом:
Локальный IP-адрес в Линукс
Чтобы получить нужные данные, достаточно воспользоваться специальной командой в терминале дистрибутива Линукс:
Утилита выведет информацию обо всех интерфейсах и их адреса.
Более подробно о параметрах можно посмотреть в другой статье https://www.vseprolinux.ru/komanda-ip
Такая команда работает в разных версиях Линукс, таких как ubuntu, debian, centos.
В появившемся окне также можно увидеть множество дополнительных данных об интерфейсах: маска сети, некоторые статистические данные. Если не получается самостоятельно найти локальный адрес в окошке, обратите внимание на цифры, указанные после слов «inet». Это и есть искомый IP.
Чтобы вывести на экран окно, содержащее исключительно IP-адреса, выполните команду:
# ip a | grep inet
Узнать IP address можно с помощью команды «ifconfig», однако она считается устаревшей и в большинство дистрибутивов она не установлена по умолчанию.
Как узнать Внешний IP-адрес
Основная загвоздка заключается в том, что пользователь устройства не имеет доступа к серверу своего поставщика услуг. Это решало бы проблему одним махом, но такой возможности нет. Юзеру нужно искать обходные пути.
Как это сделать:
- Откройте любой специальный сайт, который может распознать IP-адрес вашего устройства. Как вариант, можно в браузере ввести в любой поисковой системе фразу «мой ip»;
- Альтернативный вариант: запустите терминал Линукс и укажите в нем команду wget.
Узнать IP версии 4:
wget -qO- eth0.me
IP версии 6:
$ wget -qO- ident.me
Если есть необходимость выяснить IP-адрес маршрутизатора, то придется действовать иным методом. Чтобы получить нужную информацию, внимательно ознакомьтесь с настройками гаджета.
Заключение
IP-адрес Линукс может потребоваться юзеру в различных ситуациях. Новичку нужно внимательно разобраться с типами адресов, чтобы понять специфику данного вопроса. Воспользовавшись нашими рекомендациями, вы быстро выявите способ получения важной информации о своем компьютере, функционирующем на базе популярной операционной системы Linux. Все эти способы указаны в статье. Совсем немного практики – и задача уже не кажется такой сложной, как это было в начале.
Источник