- Как узнать IP-адрес Linux
- Немного теории
- Как узнать внутренний IP Linux
- Как узнать локальный IP в Linux
- Как узнать внешний IP-адрес в Linux
- Выводы
- How To Find IP Address In Linux
- What is IP Address?
- 1. Find IP address in Linux from Command line interface (CLI) using ip command
- 1.1. Display IP address of all network interfaces
- 1.2. Display IP address of specific network interface
- 1.3. Print only basic IP information in a tabular format
- 1.4. Display IP addresses in color
- 1.5. Display IPv4 addresses only
- 1.6. Display IPv6 addresses only
- 1.7. Print ip command output in JSON format
- 1.8. Show IP information in human readable format
- 2. Display IP address in Linux using hostname command
- 3. Get IP address in Linux from Graphical user interface (GUI)
Как узнать IP-адрес Linux
Каждый компьютер в сети интернет нужно определённым образом идентифицировать. Для этого используются IP-адреса. Каждый компьютер, подключённый к интернету, имеет свой адрес, с помощью которого можно очень просто обратиться к этому компьютеру.
Если вы хотите каким-либо образом взаимодействовать с другим компьютером по Сети, вам нужно узнать его IP-адрес Linux. Очень часто приходится работать по IP-адресу с серверами, но это может быть полезно и для домашних компьютеров, и для локальных сетей. В этой небольшой статье мы рассмотрим, как узнать IP Linux разными способами. Поговорим о том, как узнать внешний IP, выданный провайдером, и внутренний IP в вашей локальной сети. Но сначала давайте попытаемся понять, что такое IP-адрес, и как всё работает.
Немного теории
Мы можем выделить три типа IP-адресов, с которыми вам придётся сталкиваться:
- Внутренний адрес (IP-адрес компьютера);
- Адрес в локальной сети;
- Внешний IP доступный во всём интернете.
Внутренний IP-адрес нужен для того, чтобы программы могли взаимодействовать между собой в пределах этого компьютера, используя сетевые протоколы. Например, так браузер может получить доступ к локальному web-серверу или mysql-серверу. Внутренний IP довольно часто используется в системных утилитах, и узнать его очень просто — он всегда одинаковый — 127.0.0.1.
Но с локальной сетью всё немного сложнее. В идеале, каждый компьютер в мире должен был бы иметь уникальный IP-адрес для полноценного доступа в интернет. Но с ростом популярности этой технологии свободные адреса скоро начали заканчиваться, и теперь уникальные IP имеют только серверы, а обычные пользователи размещаются провайдерами по несколько сотен на одном IP с помощью NAT.
Технология NAT позволяет компьютеру подключиться к любому серверу в интернете и получить от него ответ, но инициировать подключение к такому компьютеру невозможно, поскольку фактически один IP принадлежит сотне компьютеров, и система просто не знает, к какому из них обращаются.
Ваша локальная сеть тоже работает по принципу NAT, и задача у неё похожая — защитить ваши домашние устройства от несанкционированного доступа, и позволить вам подключать к сети несколько устройств, например два ноутбука. Если бы не было NAT, вам бы пришлось покупать два отдельных интернет подключения для каждого из них.
Как вы поняли, ваш домашний компьютер мог бы иметь внешний IP-адрес доступный всем, но это нецелесообразно как минимум по двум причинам. Во-первых, дорого, во-вторых, очень небезопасно. Поэтому подключение компьютера к интернету сейчас выглядит приблизительно так:
- Внешний и доступный всем IP, который принадлежит провайдеру и используется для выхода в интернет сотен пользователей;
- IP-адрес вашего роутера в локальной сети провайдера, той самой, с IP-адресом которой вы выходите в интернет. Он не доступен из интернета и, скорее всего, вам не понадобится;
- IP-адрес вашего компьютера в локальной (домашней) сети, созданной роутером, к которой вы можете подключать свои устройства. Именно он используется для взаимодействия между устройствами в локальной сети и отображается в информации о сетевом интерфейсе;
- Внутренний IP-адрес компьютера, недоступный извне и используемый только для внутренних коммуникаций в системе.
Теперь, когда вы немного начали ориентироваться в вопросе, давайте рассмотрим способы узнать свой IP Linux.
Как узнать внутренний IP Linux
Как я уже сказал, внутренний IP всегда одинаковый для каждого компьютера — 127.0.0.1, что спрведливо не только для Linux, но и для Windows и других операционных систем. Также к своему компьютеру можно обратиться по домену localhost.
Вы можете убедится в этом, выполнив nslookup:
Как узнать локальный IP в Linux
Узнать локальный IP компьютера тоже не очень сложно. Для этого вам не нужны никакие сервисы, мы можем просто посмотреть информацию об интерфейсах.
Чтобы узнать свой IP Linux в локальной сети? выполните такую команду:
Здесь отображается довольно много информации о сетевых интерфейсах. Кроме IP, здесь можно увидеть MAC-адрес, маску сети и небольшую статистику по работе интерфейса. IP-адрес каждого интерфейса отображается после слов inet addr.
Теперь про интерфейсы: lo — это внутренний интерфейс с IP-адресом 127.0.0.1, eth0 — это проводной интерфейс, а wlan0 — интерфейс Wi-Fi. Как видите, для каждого из них установлены свои адреса.
Вы можете отфильтровать лишнюю информацию и вывести только IP-адреса:
sudo ifconfig | grep «inet addr»
Утилита ifconfig уже считается устаревшей и в некоторых дистрибутивах не используется. Вместо неё предлагается новый инструмент — ip. Вы можете выполнить аналогичные действия с помощью него:
Здесь IP-адрес отображается после слова inet. Вы знаете, как посмотреть IP-адрес Linux для компьютера в локальной сети, теперь рассмотрим внешний.
Как узнать внешний IP-адрес в Linux
С внешним IP-адресом ситуация немного сложнее. Конечно, если бы у вас был доступ к серверу провайдера, вы бы могли выполнить ту же самую команду ifconfig и узнать внешний IP Linux точно так же, как и на своём компьютере.
Понятное дело, что доступа к серверам провайдера у вас нет, поэтому придётся пользоваться обходными путями. Мы можем открыть специальный сайт, который посмотрит, с какого IP мы его открыли, и скажет его нам. Есть несколько таких сайтов. Проще всего сделать это с помощью браузера, например, откройте сайт ifconfig.me или eth0.me:
Но это не совсем удобно. Лучше сделать это с помощью терминала. Просто используйте команду wget. Сразу рассмотрим несколько таких сайтов, чтобы вы могли использовать любой понравившийся из них:
wget -qO- eth0.me
wget -qO- ipinfo.io/ip
wget -qO- ipecho.net/plain
wget -qO- icanhazip.com
wget -qO- ipecho.net
wget -qO- ident.me
wget -qO- myip.gelma.net
Чтобы не набирать длинную команду каждый раз, вы можете создать удобный алиас:
alias getip=»wget -qO — eth0.me»
Хочу заметить, что если вы хотите узнать не внешний IP компьютера, а именно адрес роутера в сети провайдера, то такой способ не поможет. Вам нужно посмотреть в настройках роутера или попытаться сделать это через командный интерфейс роутера, так как это описано в предыдущем варианте.
Выводы
Вот и всё, теперь вы точно знаете, как узнать IP-адрес Linux, оказывается, это не так сложно, как могло показаться сразу. Правда, во всех этих терминах можно сначала запутаться, но с практикой это проходит. Если у вас остались вопросы, спрашивайте в комментариях!
В статье мы рассмотрели, что такое IP-адрес, но маршрутизацию затронули только вскользь. Если вы хотите узнать об этом подробнее, то можете посмотреть вот это видео:
Источник
How To Find IP Address In Linux
This guide will walk you through the steps to check or find IP address in Linux using ip and hostname commands from command line interface and graphical user interface. In addition, you will also learn how to display only IPv4 or IPv6 addresses with example commands.
Before getting into the topic, let us have a brief look at what IP address is, and its versions.
What is IP Address?
An IP address is an unique numerical representation assigned to each device connected to a computer network. IP stands for Internet Protocol.
IP address is mainly used to identify a device and communicate with it from other devices on the local area network (LAN) and on the Internet (WAN).
There are two IP versions available:
- Internet Protocol version 4 (IPv4 in short)
- Internet Protocol version 6 (IPv6).
A typical IPv4 address is a string of numbers separated by a dot (period). Here is an example of IPv4:
A typical IPv6 address is string of alphanumeric characters. So, It consists of both numbers and characters like below:
The IP addresses are not random numbers. They are allocated and managed globally by the Internet Assigned Numbers Authority (IANA), a division of the Internet Corporation for Assigned Names and Numbers (ICANN).
Hope you got the basic idea of IP address and the organization behind it. Now let us go ahead and see how to get IP address in Linux system from command line using ip and hostname commands. First, let us look into the ip command.
1. Find IP address in Linux from Command line interface (CLI) using ip command
The ip utility is a command line network configuration tool that makes use of the full range networking of features available in modern Linux kernels. It replaces the earlier and now deprecated ifconfig program. With ip command, we can examine a Linux system’s network interfaces and routing table.
1.1. Display IP address of all network interfaces
To find IP address of all attached network interfaces in a Linux machine, run ip command with addr argument like below:
This command will display the current IP assignments to all the network interfaces in the system:
Find IP address in Linux using ip command
As you see in above output, my Alpine Linux system has two network interfaces, namely lo and eth0 . The lo is the loopback interface, a virtual interface that the system uses to «talk to itself». And the second interface called eth0 , is the Ethernet interface.
You will see the presence of a valid IP address in the inet field in the above output. As per the output, the IPv4 address of eth0 is 10.0.2.15 and IPv6 is fe80::a00:27ff:fe8f:511 .
For systems using Dynamic Host Configuration Protocol (DHCP), a valid IP address in this field will verify that the DHCP is working.
In recent Linux distributions, the name of the network interfaces might be enp5s0 or enp0s3 . If you have wireless interface card, you will see something like wlp9s0 in the output.
Did you notice the the word «UP» in the first line for each interface? It indicates that the network interface is enabled.
1.2. Display IP address of specific network interface
When you run ip addr command without any options, it will show you the network details of all interfaces in the system. You can, however, explicitly specify a particular network interface name to view its IP details only:
This command will show IP details of eth0 interface only:
1.3. Print only basic IP information in a tabular format
Instead of displaying all network details, we can show only brief output with -br ( -brief ) flag.
This option prints only basic information in a tabular format for better readability.
Print only basic IP information in a tabular format with ip command
This option is currently only supported by ip addr , ip addr show and ip link show commands.
1.4. Display IP addresses in color
The ip command has an option to add colors to the IP addresses. It is helpful to distinguish IP addresses from other parts in the output.
To configure color output, use -c flag:
This option will show each details in the output in different color.
Display IP addresses in color with ip command
1.5. Display IPv4 addresses only
As you may noticed in the previous outputs, the ip command gets you both IPv4 and IPv6 details. You can also display only IPv4 addresses or IPv6 addresses.
To print only the IPv4 addresses, use -4 option:
Sample output:
1.6. Display IPv6 addresses only
To print only the IPv4 addresses, use -6 option:
Sample output:
1.7. Print ip command output in JSON format
You can use -j ( -json ) with ip command to output results in JavaScript Object Notation (JSON) format.
Sample output:
Print ip command output in JSON format
1.8. Show IP information in human readable format
The -h , -human , -human-readable option allows you to show output statistics with human readable values followed by suffix.
For more details, check man pages.
2. Display IP address in Linux using hostname command
A hostname is a alphanumeric label assigned to a node in-order to identify it on the network. In Linux, the hostname command allows you to show or set a system’s hostname, and show network addresses of all network interfaces in the host system.
To display IP addresses of all attached network interface cards in Linux, run hostname command with -I option:
Sample output:
Display IP address in Linux using hostname command
You now learned about two commands to check IP address information from Terminal in Linux. As you can see, all of the aforementioned steps are for commandline interface (CLI) only. The following section shows how to get IP address details from a graphical environment.
3. Get IP address in Linux from Graphical user interface (GUI)
Finding IP address differs depending upon the desktop environment (DE) you use. The steps provided below are tested in Ubuntu GNOME desktop.
In the Dash menu, type Settings and click on it to open.
Open Settings in Ubuntu GNOME desktop
Next, choose network type (Wifi or Wired) you are currently using.
If you are connected to a Wired network, click on Network button in the left pane of the Settings window. On the right pane, click the Advanced network settings gear button.
Open Wired network settings
Note: My system is not connected with any wired networks, so it shows — Cable unplugged. If you’re connected with wired network, you will see Connected message.
If your system is connected to a Wireless network, click on Wi-Fi button in the left pane of the Settings window. On the right pane, click the Advanced network settings gear button.
Open Wifi network settings
Once you clicked on the Advanced network settings gear button, the following window will open. Under the Details tab, you can find the IP address details.
Get IP address in Linux from Graphical user interface (GUI)
Hope this helps.
Related guides:
Featured image by Jorge Guillen from Pixabay.
Источник