Command line show ip address linux

4 Ways to Find Server Public IP Address in Linux Terminal

In computer networking, an IP (Internet Protocol) address is a numerical identifier assigned permanently or temporarily to every device connected to a network that uses the Internet Protocol for communication. Its two major functions are to identify a network or host on a network and also serve for location addressing.

There are currently two versions of IP addresses: IPv4 and IPv6, which can either be private (viewable within an internal network) or public (can be seen by other machines on the Internet).

Additionally, a host can be assigned a static or dynamic IP address depending on the network configurations. In this article, we will show you 4 ways to find your Linux machine or server public IP address from the terminal in Linux.

1. Using dig Utility

dig (domain information groper) is a simple command line utility for probing DNS name servers. To find your public IP addresses, use the opendns.com resolver as in the command below:

2. Using host Utility

host command is an easy-to-use command line utility for carrying out DNS lookups. The command below will help to display your systems public IP address.

Important: The next two methods employ third party websites to display your IP address on the command line as described below.

3. Using wget Command Line Downloader

wget is a powerful command line downloader that supports various protocols like HTTP, HTTPS, FTP and many more. You can use it with third party websites to view your public IP address as follows:

4. Using cURL Command Line Downloader

curl is a popular command line tool for uploading or downloading files from a server using any of the supported protocols (HTTP, HTTPS, FILE, FTP, FTPS and others). The following commands displays your public IP address.

That’s It! You may find these following articles useful to read.

That’s all! If you have any questions or other methods to share in relation to this topic, use the feedback form below to write back to us.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Как узнать IP-адрес Linux

Каждый компьютер в сети интернет нужно определённым образом идентифицировать. Для этого используются IP-адреса. Каждый компьютер, подключённый к интернету, имеет свой адрес, с помощью которого можно очень просто обратиться к этому компьютеру.

Если вы хотите каким-либо образом взаимодействовать с другим компьютером по Сети, вам нужно узнать его IP-адрес Linux. Очень часто приходится работать по IP-адресу с серверами, но это может быть полезно и для домашних компьютеров, и для локальных сетей. В этой небольшой статье мы рассмотрим, как узнать IP Linux разными способами. Поговорим о том, как узнать внешний IP, выданный провайдером, и внутренний IP в вашей локальной сети. Но сначала давайте попытаемся понять, что такое IP-адрес, и как всё работает.

Немного теории

Мы можем выделить три типа IP-адресов, с которыми вам придётся сталкиваться:

  • Внутренний адрес (IP-адрес компьютера);
  • Адрес в локальной сети;
  • Внешний IP доступный во всём интернете.

Внутренний IP-адрес нужен для того, чтобы программы могли взаимодействовать между собой в пределах этого компьютера, используя сетевые протоколы. Например, так браузер может получить доступ к локальному web-серверу или mysql-серверу. Внутренний IP довольно часто используется в системных утилитах, и узнать его очень просто — он всегда одинаковый — 127.0.0.1.

Читайте также:  Geforce gt 420 windows 10 driver

Но с локальной сетью всё немного сложнее. В идеале, каждый компьютер в мире должен был бы иметь уникальный IP-адрес для полноценного доступа в интернет. Но с ростом популярности этой технологии свободные адреса скоро начали заканчиваться, и теперь уникальные IP имеют только серверы, а обычные пользователи размещаются провайдерами по несколько сотен на одном IP с помощью NAT.

Технология NAT позволяет компьютеру подключиться к любому серверу в интернете и получить от него ответ, но инициировать подключение к такому компьютеру невозможно, поскольку фактически один IP принадлежит сотне компьютеров, и система просто не знает, к какому из них обращаются.

Ваша локальная сеть тоже работает по принципу NAT, и задача у неё похожая — защитить ваши домашние устройства от несанкционированного доступа, и позволить вам подключать к сети несколько устройств, например два ноутбука. Если бы не было NAT, вам бы пришлось покупать два отдельных интернет подключения для каждого из них.

Как вы поняли, ваш домашний компьютер мог бы иметь внешний IP-адрес доступный всем, но это нецелесообразно как минимум по двум причинам. Во-первых, дорого, во-вторых, очень небезопасно. Поэтому подключение компьютера к интернету сейчас выглядит приблизительно так:

  1. Внешний и доступный всем IP, который принадлежит провайдеру и используется для выхода в интернет сотен пользователей;
  2. IP-адрес вашего роутера в локальной сети провайдера, той самой, с IP-адресом которой вы выходите в интернет. Он не доступен из интернета и, скорее всего, вам не понадобится;
  3. IP-адрес вашего компьютера в локальной (домашней) сети, созданной роутером, к которой вы можете подключать свои устройства. Именно он используется для взаимодействия между устройствами в локальной сети и отображается в информации о сетевом интерфейсе;
  4. Внутренний 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 компьютера, а именно адрес роутера в сети провайдера, то такой способ не поможет. Вам нужно посмотреть в настройках роутера или попытаться сделать это через командный интерфейс роутера, так как это описано в предыдущем варианте.

Читайте также:  Windows node set env

Выводы

Вот и всё, теперь вы точно знаете, как узнать IP-адрес Linux, оказывается, это не так сложно, как могло показаться сразу. Правда, во всех этих терминах можно сначала запутаться, но с практикой это проходит. Если у вас остались вопросы, спрашивайте в комментариях!

В статье мы рассмотрели, что такое IP-адрес, но маршрутизацию затронули только вскользь. Если вы хотите узнать об этом подробнее, то можете посмотреть вот это видео:

Источник

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 or Check Your IP Address in Linux

Home » Networking » How to Find or Check Your IP Address in Linux

An IP address is a codename assigned to a computer on a network. It works as a postal address, ensuring that network traffic is sent to the correct computer.

In this tutorial you will learn how to find your IP address using a Linux operating system.

Читайте также:  Чем отличается лицензионный windows от нелицензионного

  • A Linux operating system
  • Access to a terminal window/command-line (optional) (CtrlAltT, CtrlAltF2)

Find Your IP Address From the Command Line

There are a few different commands you can use to check your IP address. To run these commands, start by opening a terminal window/command line.

Using the hostname Command

One way to check your IP address from the command-line is by using the following command:

The system will display your internal IP address.

Using the ip addr Command

Check your ip address with the ip addr command:

The system will scan your hardware, and display the status for each network adapter you have. Look for an entry that says link/ether. Below it, you should see one of the following:

The entries will include one for a wired (Ethernet) adapter and a wireless (Wi-Fi) adapter. You may also have an entry for a virtual adapter. Generally, only one entry will have an IP address listed – that is the one you will want.

Note: The number after the slash – /24 and /64 – specifies the size of the network, and it helps with scanning and mapping network size.

Using the ifconfig Command

The third method to find your IP address involves using the ifconfig command. In the command line, enter the following:

The system will display all network connections – including connected, disconnected, and virtual. Look for the one labeled UP, BROADCAST, RUNNING, MULTICAST to find your IP address. This lists both IPv4 and IPv6 addresses.

Note: When you check your IP address, you may notice the term loopback. This refers to an IP address that returns traffic to the same computer. Usually, the loopback address is 127.0.0.1 . If you see that address listed, either you are looking at the wrong line, or you are not connected to the network.

Read phoenixNAP’s ultimate Linux IP command tutorial with 31 examples to learn more!

Finding Your IP Address in Linux With a GUI

If you are using a point-and-click interface to run your Linux system, you can check your IP address by following these steps:

1. Go to the Application menu and type Settings into the search bar.

2. Click on the Settings icon that appears among the results, as in the image below:

3. Next, find the Network tab in the Settings Menu and click on the Advanced Wired Settings icon.

4. This opens a new pop-up window with details on wired settings. Here you can find both your IPv4 address and your IPv6 address.

How to Find Public IP Address

To find your public IP address, reach out to an external website.

If you are using a browser, navigate to:

If you are using a command-line or terminal, use a retrieval command like curl or wget to display the external IP address:

Note: Did you know that when you use curl to connect to an insecure website, the output responds with an error? To resolve it, visit our guide on making curl ignore certificates.

What is a Public/Private IP Address?

Each computer in a network is required to have its own IP address. If two systems have the same IP address, it will generate errors on the network. Most modern networks will detect the problem and prompt you to fix it. However, older networks might get confused, trying to route traffic to both computers.

Most systems will have two different IP addresses:

  • Private IP address: This is the address used on the network. Also, it is the one you will want to use for configuring routing tools. On smaller networks, the internal IP address typically starts with 192.168.x.x. It is dynamically assigned to your computer whenever you connect.
  • Public IP address: This is the IP address that registers on a website when you visit it. When you connect to a small network, your computer connects to a router using an internal IP address. That router, in turn, connects to a bigger network (like an Internet Service Provider), which has its own IP address system.

Now you know how to find a private and public IP address in Linux using multiple methods.

Each option strikes a balance between speed and complexity. Now you have the flexibility to choose, if you only need your internal IP address, you can use the hostname method. If you need more detailed information, view our article on 31 Linux IP Commands with examples.

Источник

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