- 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
- How to find your IP address in Linux
- Every website has a unique, public IP address that can be reached by anyone and from anywhere.
- Subscribe now
- Finding your IP address in the GNOME desktop
- gnome-activities-wifi.jpg
- gnome-wi-fi-gear.png.jpg
- gnome-ip-addr.jpg
- Public and private IP addresses
- Private Ipv4 addresses
- Public Ipv4 addresses
- Finding your way with IP
- Как узнать IP-адрес Linux
- Немного теории
- Как узнать внутренний IP Linux
- Как узнать локальный IP в Linux
- Как узнать внешний IP-адрес в Linux
- Выводы
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
Источник
How to find your IP address in Linux
Every website has a unique, public IP address that can be reached by anyone and from anywhere.
Subscribe now
Get the highlights in your inbox every week.
We all use the Internet Protocol (IP) daily, whether we’re aware of it or not. For instance, any time you type a website name or a search term into your web browser, it looks up the IP address of that URL (or of a search engine) and then loads the website.
Let’s divide IP addresses into two categories: private and public. Private IP addresses are the ones your WiFi box (and company intranet) provide. They are in the range of 10.x.x.x, 172.16.x.x-172.31.x.x, and 192.168.x.x, where x=0 to 255. Public IP addresses, as the name suggests, are «public» and you can reach them from anywhere in the world. Every website has a unique IP address that can be reached by anyone and from anywhere; that is considered a public IP address.
IPv4 addresses have the format x.x.x.x, where x=0 to 255. There are 2 ^32 (approximately 4 billion) possible IPv4 addresses.
IPv6 addresses have a more complex format using hex numbers. The total number of bits is 128, which means there are 2 ^128 —340 undecillion!—possible IPv6 addresses. IPv6 was introduced to tackle the foreseeable exhaustion of IPv4 addresses in the near future.
As a network engineer, I recommend not sharing your machine’s public IP address with anyone. Your WiFi router has a public IP, which is the WAN (wide-area network) IP address, and it will be the same for any device connected to that WiFi. All the devices connected to the same WiFi have private IP addresses locally identified by the range provided above. For example, my laptop is connected with the IP address 192.168.0.5, and my phone is connected with 192.168.0.8. These are private IP addresses, but both would have the same public IP address.
The following commands will get you the IP address list to find public IP addresses for your machine:
- curl ifconfig.me
- curl -4/-6 icanhazip.com
- curl ipinfo.io/ip
- curl api.ipify.org
- curl checkip.dyndns.org
- dig +short myip.opendns.com @resolver1.opendns.com
- host myip.opendns.com resolver1.opendns.com
- curl ident.me
- curl bot.whatismyipaddress.com
- curl ipecho.net/plain
The following commands will get you the private IP address of your interfaces:
- ifconfig -a
- ip addr (ip a)
- hostname -I | awk ‘
‘ - ip route get 1.2.3.4 | awk ‘
‘ - (Fedora) Wifi-Settings→ click the setting icon next to the Wifi name that you are connected to → Ipv4 and Ipv6 both can be seen
- nmcli -p device show
Note: Some utilities need to be installed on your system based on the Linux distro you are using. Also, some of the noted commands use a third-party website to get the IP
Finding your IP address in the GNOME desktop
If you’re using Linux, you can find your IP address using some basic desktop utilities. First, go to your Activities screen and type Network (for a wired connection) or Wi-Fi (for wireless).
gnome-activities-wifi.jpg
In the Networks settings window, click the Gear icon next to the network you’re on.
gnome-wi-fi-gear.png.jpg
Your IP address is listed in the Network profile.
gnome-ip-addr.jpg
In this example screenshot, my IPv4 address is 10.1.1.2 and the gateway is 10.1.1.1.
Public and private IP addresses
To understand the significance of public and private IP addresses, let’s have a look at a concept called NAT (Network Address Translation) and PAT (Port Address Translation).
Private addresses are used in Local Area Networks (LAN). They are bound to a specific network.
Public addresses are necessary for establishing external connectivity to other networks, most notably the «Worldwide Web» (www) of the Internet.
NAT is a translation of a private IP to a public one, and consists of three major types: static, dynamic, and PAT. In static NAT, one private IP is mapped to one public IP. A common example ru ydco is a firewall. In dynamic NAT, a private IP address is mapped to a public IP but from a pool of public IP addresses.
With a total of 2^32 IPv4 addresses, out of which approximately just 3.7 billion are public addresses, there are literally more people and devices than there are IP addresses. And yet we haven’t run out of addresses. That’s because of a concept called PAT, which allows for a single public IP address to be translated from multiple (generally all) private IP addresses using port numbers. Here, instead of assigning a public address to each device, a single public address is allocated to the external side, and private addresses are assigned to each device within the internal network. PAT is most widely used in residential wireless routers, which we use to connect to the Internet.
Private Ipv4 addresses
Local addresses are only used within an internal network.
The range is 10.x.x.x, 172.16.x.x-172.31.x.x, and 192.168.x.x, (x is a number from 0 to 255).
Used in Local Area Networks (LAN).
Not globally reachable, and cannot be searched globally.
Not unique: the same private IP can be used in two different networks.
Each router comes with a private IP address, which multiple devices can connect to. Users don’t need to pay extra to obtain a private address.
Some example private IP addresses: 10.0.0.4, 172.16.4.5, 192.168.9.8
Public Ipv4 addresses
Public addresses are used to connect to external networks.
Ranges from 0.0.0.0 to 255.255.255.255, except for private IP addresses and few unusable or reserved IPs.
Used in connecting to the Internet.
Globally reachable and can be searched. These are often used to determine geolocation.
Unique across all of the Internet.
A private address costs money because they are unique, limited, and accessible from the Internet. Each website has a domain name mapped to a public IP. For example, the public IP address for opensource.com is 54.204.39.132
Finding your way with IP
An IP address is the most direct route to a computer over a network. There are other systems, such as DNS and Avahi, to help route one computer to another, but when those are unavailable or undesired for any reason, the IP protocol is what you use. Now you understand why, and more importantly, how to find your own.
Editor’s note: This article was originally published in May 2018 and has been updated.
Источник
Как узнать 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-адрес, но маршрутизацию затронули только вскользь. Если вы хотите узнать об этом подробнее, то можете посмотреть вот это видео:
Источник