Bash как узнать ip
Перейти к содержимому

Bash как узнать ip

  • автор:

How can you display host IP address in bash prompt?

Like above, I’d like to display IPv4 address of eth0 (or part of it) in PS1 or bash. Is there a way to do this?

11 Answers 11

I use the following in my .bashrc

This will show you a prompt of:

Remove the \w to get rid of the present working directory or make it \W to make it only the a partial working directory

You can also use the following, assuming that there is only one IP address in your /etc/hosts file:

SomeGuyOnAComputer's user avatar

Disclaimer: literally no attempt made to make this less-rubbish.

Below is the way to do that.

As stated by Sirex you can do a lot of tricky things with command substitution, I would prefer the following declaration using the ip utility:

export PS1=»IP: $(ip addr show dev eth0 | grep «inet » | cut -d» » -f6) #» or something like that.

Another option is to use the tool facter which provides a lot of information about your system so a simple facter ipaddress_eth0 gives you the IP-Adress. So the new example would be

export PS1 mt24″>

I’ve taken @SomeGuyOnAComputer’s answer and improved it slightly:

IP=$( ifconfig | grep ^eth -A2 | grep ‘inet addr:’ | cut -d: -f2 | awk ‘< print $1 >‘ ) PS1=’\n\[\033[00;32m\]\u@$IP \[\033[00;33m\]\w\n\\$\[\033[00m\] ‘

I had a docker container running on my machine so it was picking up the docker’s ip address when I ran @SomeGuyOnAComputer’s command. The new version looks for the line that starts with ‘eth’ and prints the 2 lines after the matching line (-A2) information. The rest is just like @SomeGuyOnAComputer’s version.

3 Easy Ways to Find IP address in Linux

An IP address is a unique identifier assigned to a computer or device connected to the internet.

In this blog post, we will discuss three methods to find the IP address of a Linux system: using the ifconfig command, using the ip command, and using the ip route command.

Let’s get started!

Procedures to find ip address in Linux

  • Open the terminal application.
  • Type ifconfig -a or ip addr or ip route command
  • Press Enter to run the command.
  • The output will display the ip address for all the network interfaces.

Find IP address with ip addr command in Linux

The most convenient way to find ip address in Linux is using ip addr command. All we need is to open the terminal then type ip addr in the prompt and press enter.

The number next to inet is the IP address. This command will list IP address, MAC address , MTU size and other information about a network interface.

I find this command very useful, as it gives me more detailed information about my system’s IP address and the status of the network interface.

Furthermore, we can also type ip address or ip a for short.

  • ip addr – Show IP address for all interfaces
  • ip addr show dev em1 – Display information only for device em1
  • ip addr show up – Show IP address for the running interfaces

By default, the ip addr command will display ip information of all the network interfaces on the Linux system.

This is the command output in my system.

# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000
link/ether 02:3f:4d:eb:52:e7 brd ff:ff:ff:ff:ff:ff
inet 10.1.0.143/24 brd 10.1.0.255 scope global dynamic noprefixroute eth0
valid_lft 3198sec preferred_lft 3198sec

3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether fa:16:3e:18:3a:76 brd ff:ff:ff:ff:ff:ff
inet 10.254.222.37/23 brd 10.254.223.255 scope global dynamic eth0
valid_lft 70000sec preferred_lft 70000sec

From the above example, we can see that there are three network interfaces l0, eth0 and eth1.

The ip address for eth0 is 10.1.0.143 and the ip address for eth1 is 10.254.222.37.

This output is easily understood.

  • The inet entry displays the IP address for the interface.
  • UP signifies that the interface is ready for use;
  • Brd denotes that the interface is connected to a network that supports broadcast messaging (ethernet)
  • LOOPBACK shows which device (lo) is the loopback address.
  • The maximum transmission unit (MTU) on eth0 is 1500 bytes. This determines the size of the largest packet that can be transmitted over this interface (and is sometimes “tuned” to other values for performance enhancement).

If you have more than one network interface on your system, you can use ip addr show dev command to view the IP address of the specific interface.

The syntax for this command is:

ip addr show dev interface_name

Let’s say if I want to find the ip address of interface eth1, I will use the following command:

$ ip addr show dev eth1
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether fa:16:3e:18:3a:76 brd ff:ff:ff:ff:ff:ff
inet 10.254.222.37/23 brd 10.254.223.255 scope global dynamic eth0
valid_lft 69786sec preferred_lft 69786sec

Additionally, I would like to share another command ip addr show up.

The “ip addr show up” command is used to display the network interfaces that are currently in an “up” state, which means that they are enabled and active.

There are a number of other options that you can use with the ip addr command. For more information, you can type command ip addr help.

To learn more about ip command, I would recommend the following article.

Get Ip address with ifconfig command in Linux

The ifconfig command is a common command that is used to view IP related information in Linux. The command output includes the interface name, its assigned IP address, netmask, broadcast address, and other network-related information.

If no argument is given, this command displays the configuration details of all active network interfaces on the system.

In addition to that, if you are only interested in certain interface eth0, use: ifconfig eth0

To use this command, just type ifconfig in the shell prompt and press enter.

# ifconfig -a
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 9001
inet 10.1.0.143 netmask 255.255.255.0 broadcast 10.1.0.255
ether 02:3f:4d:eb:52:e7 txqueuelen 1000 (Ethernet)
RX packets 1142453 bytes 77488923 (73.8 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 5835535 bytes 8505814381 (7.9 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

The ifconfig command is a powerful network configuration utility that can be used to display or configure a network interface.

Furthermore, it should be noted that ifconfig command is considered as deprecated command and it is replaced by iproute2 package in many distributions.

This means that it may not be supported in newer versions of the operating system and it may not be compatible with some distributions.

If you need to install it, you can follow this guide.

Get Ip address with ip route command in Linux

The ip route command can be used to find the IP address of a Linux system.

This command will print out the IP address of our system along with other network details. Once we execute the command we will see an output similar to the text below.

$ ip route
default via 10.1.0.1 dev eth0 proto dhcp metric 100
10.1.0.0/24 dev eth0 proto kernel scope link src 10.1.0.143 metric 100

The information shows us the server’s IP routing table and network gateway.

On these lines, the IP address following `src` are the IP(s) configured on the server.

In the example above, we can see that the server has an IP address of `10.1.0.143`.

Check IP address with Bash script in Linux

We can get a list of the network interfaces and IPv4 addresses on our server by running the following command:

ip -4 -o a | cut -d ‘ ‘ -f 2,7 | cut -d ‘/’ -f 1

The output lists the interface names on the left and the associated IP addresses on the right.

lo 127.0.0.1
eth0 10.1.0.79

Let’s break down the command:

ip -4 -o a : output each record on a single line, replacing line feeds with the ‘\’ character. This is convenient when you want to get ip address in bash script .

The cut command is used to extract a subset of the lines from a command output, or to extract a subset of the columns.

The “-d” parameter specifies the delimiter that is used to separate the fields.

The “-f” parameter specifies the field number(s) that you want to extract.

Here’s an example: cut -d’,’ -f1,3 filename.txt This command will extract the first and third column from the lines in the file filename.txt, using commas as the delimiter.

Find public IP address in Linux

The way to get your public IP address is to Google it. Type in “what is my IP address” or “how to find my IP address,” and Google will tell you.

Your IP address is public to the internet. We can get it from many online tools. It can be easily tracked by others.

Alternatively, you can try using curl to access an external service that will detect your public IP. There are quite a few out there – I just went with the first search result I found:

ip_addr: 64.104.44.110
remote_host: unavailable
user_agent: curl/7.84.0
port: 35116
language:
referer:
connection:
keep_alive:
method: GET
encoding:
mime: */*
charset:
via: 1.1 google
forwarded: 64.104.44.110, 34.160.111.145,35.191.8.3%

There’s another way to determine your public IP address. Perform a DNS lookup against myip.opendns.com. It’s a service provided by OpenDNS and it’s lightening fast!

dig +short myip.opendns.com @resolver1.opendns.com
64.104.44.110

What is Ip address?

From Wikipedia, IP address is used in a system for communication. It is a numerical label such as 192.0.2.1. An IP address serves two main functions: network interface identification and location addressing.

An IP address is the identifier that enables our device to send or receive data packets across the internet. It holds information related to our location and therefore making devices available for two-way communication.

Most internet service providers still use IPv4. It’s based on 32 binary bits, consists of four numbers from 0 to 255, and is separated by dots. For example, 103.86.98.1.

A Linux server can have more than one network interface. This is often the case with web servers and other devices that need to be able to connect to different networks. For example, a web server may need to be able to connect to both the internet and a local network.

A network interface can have more than one IP address. The first address is called the primary address, while the others are called secondary addresses or aliases. Using secondary IP addresses is common with web servers.

For example, a web server may have a primary IP address that is used to connect to the internet and a secondary IP address that is used to connect to a local network. This allows the server to be reachable from both networks.

In the following example, there are two IP addresses 10.252.10.51 and 10.252.10.52 on the physical interface eth0.

eth0 Link encap:Ethernet HWaddr 00:50:56:8F:44:C7
inet addr:10.252.10.51 Bcast:10.252.10.255 Mask:255.255.255.0
eth0:0 Link encap:Ethernet HWaddr 00:50:56:8F:44:C7
inet addr:10.252.10.52 Bcast:10.252.10.255 Mask:255.255.255.0

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

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

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

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

Сначала давайте попытаемся понять, что такое IP-адрес, и как всё работает. Мы можем выделить три типа IP-адресов, с которыми вам придётся сталкиваться:

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

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

С локальной сетью всё немного сложнее. Интернет, это не одноранговая сеть, где все компьютеры соединены между собой на одном уровне, а множество отдельных сетей, соединённых между собой с помощью маршрутизаторов. Если ваш компьютер подключен к интернету по проводу, то здесь у вас есть марштуризатор, к которому можно подключить несколько устройств. Например, компьютер, ноутбук и смартфон. Сеть роутера называется локальной и в этой сети у компьютера есть IP адрес, который вы можете использовать для доступа к нему из других устройств в этой сети. Но для провайдера и внешнего интернета у всех этих устройств будет один IP адрес — адрес роутера.

Теперь давайте разберемся с внешним IP адресом. Точно так же как вы подключаете несколько своих устройств в локальной сети, так и провайдер объединяет своих клиентов в локальную сеть и для внешнего интернета у них на всех один IP адрес. Так было сделано потому что с ростом популярности этой технологии свободные адреса скоро начали заканчиваться, и теперь уникальные IP имеют только серверы, а обычные пользователи размещаются провайдерами по несколько сотен на одном IP с помощью NAT. Этот IP адрес считается внешним.

Одно время, провайдеры раздавали пользователям динамические IP, которые были уникальными и менялись при перезагрузке роутера. По ним можно было получить доступ к компьютеру из интернета после небольшой настройки роутера, но потом начали использовать технологию NAT для того чтобы разместить много пользователей на одном адресе. Но это не большая проблема. Так компьютеры домашних пользователей находятся в большей безопасности, а если к ним нужно получить доступ то существуют такие сервисы как Ngrok, а также можно использовать VPN.

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

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

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

Теперь, когда вы немного начали ориентироваться в вопросе, давайте рассмотрим способы узнать свой IP Linux.

Как узнать внутренний IP Linux

Как я уже сказал, внутренний IP всегда одинаковый для каждого компьютера — 127.0.0.1, что справедливо не только для Linux, но и для Windows и других операционных систем. Вообще, все IP адреса от 127.0.0.1 до 127.255.255.255 привязаны к локальному сетевому интерфейсу и используются для взаимодействия с текущим компьютером.

Также к своему компьютеру можно обратиться по домену localhost. Вы можете убедится в этом, выполнив команду ping:

ping localhost

Как узнать IP в локальной сети в Linux

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

ip -br a

Опция -br включает сокращенный режим вывода, а a — это сокращение от address, команды которая позволяет управлять сетевыми адресами. По синтаксису туда ещё желательно добавить команду show, но она и так используется по умолчанию. Вот так будет выглядеть полная команда:

ip —brief address show

Здесь выводится только список сетевых интерфейсов их состояние и IP адрес. Вот их описание:

  • lo — локальный сетевой интерфейс, который всегда указывает на текущий компьютер;
  • enp* — проводной сетевой интерфейс, расшифровывается как Enthernet PCI. Также может использоваться имя eth*.
  • wlp* — беспроводной сетевой интерфейс WiFi, расшифровывается как Wireless PCI. Также может использоваться имя wlan*.

В данном случае проводной интерфейс называется enp3s0 и вы можете видеть его IP адрес в третьей колонке. Вы также можете получить IP для конкретного сетевого интерфейса. Например для enp0s3:

ip —brief address show device enp0s3

Также можно отфильтровать только IP адрес с помощью awk:

ip —brief address show device enp0s3 | awk ‘‘ | cut -d’/’ -f1

IP адреса в локальной сети должны находится в таких диапазонах:

  • От 192.168.0.0 до 192.168.255.255
  • От 10.0.0.0 до 10.255.255.255
  • От 172.16.0.0 до 172.31.255.255
  • От 100.64.0.0 до 100.127.255.255

Эти адреса зарезервированы для локальных сетей и в качестве публичных адресов использоваться не могут.

Вы также можете использовать устаревшую команду ifconfig. Здесь отображается довольно много информации: MAC-адрес, маску сети и небольшую статистику по работе интерфейса. Сам IP адрес отображается после слова inet:

sudo ifconfig

Вы можете отфильтровать лишнюю информацию и вывести только IP-адреса:

sudo ifconfig | grep «inet»

Как узнать внешний IP-адрес в Linux

Для того чтобы узнать внешний IP адресе вы можете открыть специальный сайт, который посмотрит, с какого IP вы его открыли, и скажет его вам. Есть довольно много таких сайтов. Проще всего сделать это с помощью браузера, например, откройте сайт ifconfig.me:

Но это не всегда удобно. Лучше сделать это с помощью терминала. Просто используйте команду curl или wget. Сразу рассмотрим несколько таких сайтов, чтобы вы могли использовать любой понравившийся из них:

wget -qO- ifconfig.me curl ifconfig.me curl ipinfo.io/ip curl ipecho.net/plain curl icanhazip.com curl ipecho.net/plain curl ident.me curl api.ipify.org

Чтобы не набирать длинную команду каждый раз, вы можете создать удобный алиас:

alias getip=»curl ifconfig.me»

Хочу заметить, что если вы хотите узнать не внешний IP компьютера, а именно адрес роутера в сети провайдера, то такой способ не поможет. Вам нужно посмотреть в настройках роутера или попытаться сделать это через командный интерфейс роутера, так как это описано в предыдущем варианте.

Выводы

Теперь вы знаете, как узнать IP-адрес Linux, оказывается, это не так сложно, как могло показаться сразу. Вы ещё можете использовать утилиту hostname с опцией -I для получения всех сетевых адресов привязанных к вашему компьютеру, а также можете найти адрес IP адрес в графическом интерфейсе NetworkManager или с помощью его консольной утилиты nmcli. Но описанные в статье способы более универсальны и просты. А какой способ используете вы? Напишите в комментариях!

Как определить ip через bash скрипт?

Как мне сделать так, чтобы я мог в скрипте написать например $ip и чтобы в конфиги прописался ip сервера в терминале которого был запущен скрипт. Такого плана хочу сделать:

echo «host $ip» > /etc/rclocal

  • Вопрос задан более трёх лет назад
  • 10567 просмотров
  • Facebook
  • Вконтакте
  • Twitter

У сервера может быть несколько IP адресов, несколько интерфейсов, и работать они могут с разными маршрутами.
Вы что именно хотите?
ifconfig пропарсить? или ip addr show?

Если внешний интерфейс один, то подойдет обычный
hostname -I

  • Facebook
  • Вконтакте
  • Twitter

zolt85

Если известно наименование интерфейса, то можно попробовать так

Опять же, это будет адекватно работать если интерфейс один (исключая lo), если таких интерфейсов несколько, то нужно что-то по серьезнее писать.

  • Facebook
  • Вконтакте
  • Twitter

zolt85

CityCat4

В самом наипростейшем случае, когда одна сетевуха, никаких наворотов — сначала netstat -in, чтобы получить список интерфейсов и их имен и откинуть lo0, а потом ifconfig по тому интерфейсу, который остался.
Но это наипростейший случай. Даже у компа с одной сетевухой может быть например виртуальная машина и мост, который обьединяет уже как минимум два интерефейса:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *