- Как узнать IP-адрес Linux
- Немного теории
- Как узнать внутренний IP Linux
- Как узнать локальный IP в Linux
- Как узнать внешний IP-адрес в Linux
- Выводы
- How to Check IP Address on Linux using Command Line
- What is an IP Address?
- Method 1 – Using ifconfig Command
- Method 2 – Using ip Command
- Bash Shell Command to Find or Get IP address
- Bash Shell Command to Find or Get IP address
- Displaying private IP addresses of FreeBSD Unix server using the ifconfig
- Finding default routing information on Unix
- Find the IP address of the local machine on Linux using hostname
- Linux ip Command
- Linux command to display default routes
- Bash command for showing the public IP address of Linux and Unix systems
- Conclusion
Как узнать 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 Check IP Address on Linux using Command Line
How to check IP address on Linux machine using the command line interface? Mostly all of the Linux and Unix operating systems provides ifconfig and ip binary files. You can simply use these commands to find the local system IP address.
What is an IP Address?
A Internet Protocol address (IP address) is the numerical label assigned to each hardware devices connected to a computer network that uses the Internet Protocol to identify the devices. In general terms, it is an identity of any device. An IP address allows a device to communicate with other devices over an IP-based network like the LAN or Internet.
Method 1 – Using ifconfig Command
ifconfig command is generally available under /sbin directory. So you will need root or sudo access to run this on many of operating systems.
Sample output: [Some output hidden]
As per above output, this system has IP address 192.168.10.199 on Ethernet interface eth0.
You can also view the specific interface details by specifying the interface name on the command line as below.
Method 2 – Using ip Command
ip command generally available under /bin directory but some Linux os keep is under /sbin directory. Use the following command to get ip address using ip command.
Sample output: [Some output hidden]
As per the above output, this system has IP address 192.168.10.199 on Ethernet interface eth0. The interface eth1 doesn’t configure with an IP address.
You can also view the specific itnerface details using below command
Find more commands to check local ip address of any Linux system.
Источник
Bash Shell Command to Find or Get IP address
Bash Shell Command to Find or Get IP address
If no arguments are given to ifconfig command, it displays the status of the currently active interfaces. It shows an Ethernet IP address, Mac address, subnet mask, and other information. Type the following /sbin/ipconfig command to display IP address and releated networking information:
$ /sbin/ifconfig
OR type the following command:
$ /sbin/ifconfig | less
Under Solaris and other Unixish oses you may need to type ifconfig command with -a option as follows:
$ /sbin/ifconfig -a
Sample outputs:
In the above example, 192.168.1.2 is the IP address of the eth0 Ethernet interface. Of course, NIC (network interface card) name will be different as per your version of Unix system and network card driver. Here is an output from my macOS Unix based desktop:
/sbin/ifconfig
/sbin/ifconfig en0
Displaying private IP addresses of FreeBSD Unix server using the ifconfig
Simply run:
ifconfig
ifconfig -a
ifconfig em0
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Finding default routing information on Unix
We need to type the following command:
# netstat -rn
FreeBSD Unix Default Route
Find the IP address of the local machine on Linux using hostname
We can determine the IP address or addresses of the Linux server by using the hostname command too. Open the Terminal application and execute the hostname command as follows:
# hostname -I
Sample outputs:
Linux ip Command
Enter the following command to list all network interfaces from bash shell:
# ip link show
Linux command to display default routes
The syntax is as follows:
ip route show
ip r s
route -n
Bash command for showing the public IP address of Linux and Unix systems
We can use the host command or dig command as follows to display the public IP address of your Linux or Unix system:
host myip.opendns.com resolver1.opendns.com
OR
dig +short myip.opendns.com @resolver1.opendns.com
How To Find My Public IP Address From Command Line On a Linux
Conclusion
You learned various bash commands to find both private and public IP addresses, netmask, default route, and other information. For more information please see howto read UNIX/Linux system IP address in a shell script.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
ipconfig usually doesn’t work outside of windows
Opps! Just corrected typo since I work on both UNIX and Windows Server and sometime I get confused :(.
Thanks, I appreciate your post 🙂
i worked in a company and the I.T man close the face book site what can i do
Work saeed and don`t be a facebook adict
Use
hostname -i
hostname -I
also find other parameters using man hostname.
hostname -i doen’t get the internet ip address:
# hostname -i
127.0.0.2
it gives me the lo ip address.
I want to get the internet ip address from a command.
I have found this way to get my ip public address (I have two IPs in my eth0 card for NAT):
xxxx:
I’m trying OpenSuSE LiveCD 64Bits (Linux linux 2.6.25.5-1.1-default #1 SMP 2008-06-07 01:55:22 +0200 x86_64 x86_64 x86_64 GNU/Linux)
and the previous command doesn’t work. I have different broadcast address, so I get it with the mask (that is the same):
linux:/home/linux # ifconfig eth0 | sed -n “/inet addr:.*255.255.248.0/”
xxx.xxx.xxx.xxx
linux:/home/linux #
# ifconfig eth0 | grep inet | awk ‘
Where eth0 is the interface you want to know the ip address. In my case was eth0. This will retrieve the Ip Address from the specified interface. If you have ipv6 active and you only use ipv4 Address, then add a grep . to the end of the sentence.
it would be like this:
root@azrael:
# ifconfig eth0 | grep inet | awk ‘
I use the above to retrieve the Ip address (dynamic one) from my ISP in order to forward the HTTP petitions to the web server (behind a firewall). Hope it works for you.
Thanks a lot, Alejandro
almost good:
ifconfig eth0 | grep ‘inet ‘ | awk ‘
will work ->inet otherwise you will get an empty line from the inet6 line you grepped
is there any other option available to get ip address on linux
I simply issue a bash command:root@debian:
that’s why i typed two lines, the first one if you don’t have inet6 active on your server, and the second one if you do have it on.
# ifconfig eth0 | grep inet | awk ‘
Hi,
in case someone still interested, i think easiest way to get local ip address is:
hostname -I (capital i)
this will return just the ip address with nothing else.
To get my external ip address (without use dyndns, noip & c) i use in a script:
This will write to /tmp/ip.txt my external ip and then i upload the text file with curl
to a directory on my web page
Bye
Award
——————
C u in /dev/null
HOW TO CHANGE IP,SUBNETMASK,GATEWAY,PLS SEND INFORMATION IM TRYING /etc/inet/hosts
/etc/inet/ipnodes THIS COMMAND BUT IS NOT WORK PLS HELP ME
Hi, I’m using RedHat Workstation 4 and would like to write a script to set the IP address, subnet mask and hostname of my machine. The same as Rahul.
How can i do this?
Thanks in advance.
A lot of the above example scripts/commands dont work corectly due to missformatting of the various Quote characters. Single quotes, double quotes and backticks are messed up.
` is a backtick – top left of the keyboard. Its used to go around a command thats ran.
export FOO=`ls`
puts the output of the ls command in the variable FOO
single Quote ‘ and double quotes ” are used in different places to go around arguments to commands. and to keep special chaacters from gettting parsed by the shell.
oops.. Watch out for the way this thread/forum alters the matching Quote to the single and double qupte if you cut and paste the examples. ie:
single Quotes ‘hello’
double quotes “hello”
back ticks `hello`
I had to manually alter the lines after i pasted them to use proper quoteing.
how to find the ip address of an website in linux
Hi
we have server configured on Linux.
Is there any way to get the IP Address of the client which is conncetd to that server.
IP=`who -m —ips | awk ‘
Another syntax
IP=$(who -m —ips | awk ‘
Kishore , go to Terminal, and say ‘ping yahoo.com’
ifconfig eth0 | grep inet | sed -n «s/^\s*inet addr://p» | awk ‘< print $1 >‘
Works on my Linux system
This one I have used on my Ubunut 9.04 system
# ifconfig eth0|grep «inet addr:»|awk ‘
I like to use the simple and concise:
host $(hostname) | sed ‘s/.*has address //g’
It simply returns the IP address that the rest of the world sees for your machine.
@wuhaa @Alejandro\ Smith
Personally I prefer this version:
$ /sbin/ifconfig eth0 | sed ‘/inet\ /!d;s/.*r://g;s/\ .*//g’
real 0m0.027s
user 0m0.013s
sys 0m0.003s
real 0m0.009s
user 0m0.011s
sys 0m0.010s
real 0m0.005s
user 0m0.005s
sys 0m0.004s
The fewer processes, the faster the execution.
brill score! well done.
Excellent info on that.. thanks for updating this. That’s true, fewer processes translates into a faster execution.
Two years ago when i first posted on this faq with a “solution”, i was a new linux user, and i did not had any experience on this. I read some good information on bash scripting and came out with this solution for a problem i was having at that time.
I didn’t care back then if it was faster than other solutions, i just needed to solve the issue.. 😉 but of course, YOU are completely right with your point of view.
Thank you all for sharing your knowledge on this.
God bless you all.
Similar approach, but with Awk instead of sed:
Do some *nix implementations put a space after ‘addr:’ ? If so, this will break in those cases.
Excellent command to find the originating IP addresss
hostname -i
On my Ubuntu box, “hostname -i” does not give the same result as “host $(hostname)”.
Simples…
Work For me (Debian Lenny 5.0)
# ifconfig eth0 | grep inet | grep -v «inet6» | awk
Run it as
source
Now this works for Solaris 10
ifconfig -a
To find the ip address of Unix box from Unix prompt:
Here’s one that works (quickly) for me using cut:
A computer may have multiple network interfaces and therefore more than one ip-address you should try:
If you omit [dev] this command will give you a list of all IP-address and should work with English and German localization.
hostname -i is unpredictable in its result and nslookup $(hostname) will give you only what DNS knows about your machine.
its realy grtt i found my way thankss..
i have always the same result : inet iddr : 127.0.0.1
what could be the problem ) thank you
Just running the following
The result will be (on one line)
Then you can apply a simple filter on it to extract the IP
Sorry for the typos. Unable to re-edit my post.
I’m using cygwin on windows and a VPN. None of the above worked for me. I had to use the following command and some grep and sed commands
route print | egrep » 255.255.255.255.*123.123.123.123″ | sed ‘s/\s*\(.*\)255.255.255.255.*/\1/g’
### I’ve used 123.123.123.123 as a fictional router address.##
Explanation:
The vertical line, the pipe symbol, | , takes the output of everything on the left and feeds it to the command on the right. So the solution that works for me (the rest do not) involves essentially three commands – each of which that does something and parse things to the next step.
- route print : the main command of many things – over many lines
- egrep » 255.255.255.255.*123.123.123.123 : this selects a line that has the netmask at 255.255.255.255 then any characters as shown by the .* after the 255’s and then looks for my router’s address of 123.123.123.123.
- sed ‘s/\s*\(.*\)255.255.255.255.*/\1/g’ : sed command replaces/extracts text. basic use: ‘s/replace/withThis/g’ does a global search and replaces all references of replace with the string withThis. This sed command extracts the part of the line before the 255 part. It ignores leading spaces indicated by the \s and also anything after the 255 part shown by .* which is a shorthand for any character or number (the . part) that is found zero of more times (the * part). By placing part of the replace string in parentheses \(.*\) I am saying keep this part. So it’s the part after leading spaces and before the 255s. The \1 part is the replacement part of the sed command throws away all the other stuff and just keeps that part in parentheses and is displayed. This is the IP address on my machine.
Excelent post
i’m learning i’m learning .
:3
Источник