Use ifconfig.me to return your IP and Host
ifconfig.me is a web service that displays information about your connection, including IP address, hostname and User Agent string. Helpfully it provides a simplified interface that can be easily queried to get this information from the command line.
All commands are variations on the below. The full list is also available on the ifconfig.me website:
curl ifconfig.me curl ifconfig.me/<request-data>
Method
To get your remote IP address as seen by other users online enter the following at a command line:
curl ifconfig.me or curl ifconfig.me/ip
curl is a command-line tool for requesting data from a specified URL
Other commands are variations on this theme such as:
curl ifconfig.me/host for your remote hostname
curl ifconfig.me/ua for your User Agent
Note that your User Agent will be that as sent by curl and will differ from that reported when accessing ifconfig.me in your actual browser.
A full set of all the data returnable is available using:

Downloadable ebook (PDF, ePub) & Complete Source code
To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount on all books and courses.
[[ activeDiscount.description ]] I’m giving a [[ activeDiscount.discount ]]% discount on all books and courses.
Early access
Enjoyed this? Subscribe to get new updates weeks before anyone else, straight in your Inbox.
IP addresses¶
Your home computer always contains two IP addresses. How local network works is described in picture below.

Icons used in image was created by Mithun Raj on freeicons.io. Thank you 🙂
Picture was created with Firealpaca
What two addresses I mean ?
- Internal (private) IP address — router interface when connects to local network
- External (public) IP address — router interface when connects to internet
For example (see picture above) — your laptop has internal IP address 192.168.0.106 but external address is 89.35.8.107
Our home Nat router allows connections in direction from internal to external network (internet) and not vice-versa unless is used technique called port forwarding. There is no direct connection between the Internet and a computer (except port forwarding).
So no one can not to connect to your internal IP address from internet. Only port forwarding allows device to get external IP address and reach this device from internet.
Internal (private) IP address¶
About Internal IP address is RFC 1918
we can set three types of private IPv4 address:
- Class A 10.0.0.0 — 10.255.255.255 (10/8 prefix)
- Class B 172.16.0.0 — 172.31.255.255 (172.16/12 prefix)
- Class C 192.168.0.0 — 192.168.255.255 (192.168/16 prefix)
Another type of private address is 169.254.X.X — it is IPv4 Link Local Address, it is used when we connect two computer with cable. There can occure a problem when we want this pc add local IP address with DHCP . This can not allocate IP addres with DHCP because this PC will dynamicaly allocate IP address by itself. So this function can be used if we do not have a DHCP server to automatically allocate IP addres for our PC . This address is not routable so we can not route this address by internet or another subnet. This address is automatically allocate to host whene there is no DHCP server.
Internal IP addresses use a special address range from a reserved non route-able address range. This range is same for every local network. Range is restricted for local usage. So the internal IP address ranges are blocked by Internet routers, you can not see them from internet.
Internal IP addresses have these schemes in most cases:
- 192.168.0.x
- 192.168.x.0
other schemes of private IP can be:
- 10.x.x.x is a 24 bit address block
- 172.16.x.x to 172.31.x.x is a 20 bit address block.
Your router has Internal IP probably as 192.168.0.1 or 192.168.1.0
Devices in your local network have these Internal IP addresses:
- PC 192.168.0.103
- TV 192.168.0.104
- Raspberry 192.168.0.105
- laptop 192.168.0.106
You can locally connect many devices to your router. But all of these devices will have only one External IP address of your router.
How to find out your internal IP addresses on macOS¶
There are two commands to check your IP :
- ifconfig
- ipconfig
When you prompt:
you should get output of all connections:
Your output will be different in view of your OS .
For Linux distributions you get these main variables:
- eth[0-x] : ethernet interface, to connect with cable
- lo : loopback or local, when you use localhost
- wlan[0-x] : wireless interface, to connect with wifi
Output above is from macOS, there is some differents. See most of them below with explanation:
- lo0 : loopback (localhost)
- gif0 : Software Network Interface
- stf0 : 6to4 tunnel interface
- en0 : Ethernet 0 (ethernet), physical network connection
- en1 : Ethernet 1 (wireless), physical network connection
- fw0 : Firewire, IP over Firewire interface
- vmnet0 : Virtual Interface, interfaces are installed by VMware for network communication with virtual machines
- utun0 : Tunneling interface. Used for VPN connections to tunnel traffic or for software like Back To My Mack. creates VPN clients
- llw0 : Low-latency WLAN Interface. Used by the Skywalk system.
- ap1 : Access Point. This is used if you are using your MacBook as a wireless host where you are sharing its connection.
- awdl0 : Apple Wireless Direct Link. WIFI p2p connection for things like AirDrop, Airplay, etc. Also used for Bluetooth.
- llw0 : Low-latency WLAN Interface. Used by the Skywalk system
- bridge0 : Thunderbolt Bridge
If you want to get shorter output, where you will find your IP addresses easier, prompt:
It means show me all active and inactive connections and their inet. Inet means IPv4 and inet6 means IPv6. When you prompt ifconfig withou -a it shows only active connetctions see documentations or there is nice explanation to other usage for example how configure addresses to an interface etc.
- inet : IPv4
- ether : MAC address
Other approach can be use command grep with ifconfig
If you want output only as your IPv4, then prompt:
ifconfig VS ipconfig¶
ifconfig is used in UNIX OS and it means Interface Configuration. This command is the same as ipconfig, and is used to view all the current TCP / IP network configurations values of the computer
ipconfig is used in Microsoft Windows but ReactOS or macOS support this command. It means Internet Protocol Configuration. This command is used to view all the current TCP / IP network configurations values of the computer
When you dont want to use terminal for this quest you can read your internal IP address in you setting in macOS.
system preferences –> network –> Wifi –> advanced –> TCP/IP –> address IPv4
How to find all devices on your local network¶
For this purpose is the best choice to use tool called nmap
Tool nmap is not installed on macOS, so I recommend to instal via brew
After installation you have to link the tool
In my case I got a error
to fix this error use this command:
whoami : is name your current user chown : tool for change file owner and group, see man chown -R : Change the user ID and/or the group ID for the file hierarchies rooted in the files instead of just the files themselves.
When link is complete then you can scan your local network with nmap
Command to scan your all active devices in your local network is:
It search all active connections with IP pattern 192.168.0.x. It is recommended to use as sudo because if you don’t use as sudo you received very basic informations.
-sn : Ping Scan — disable port scan, also called as quick scan in older version was -sP . This option tells Nmap not to do a port scan after host discovery. If you don’t use this option, the you get result with open ports.
/24 : is referring to the subnet mask. It is CIDR format. /24 means that the first 24 bits of the IP address are part of the Network number (192.168.0) the last part is part of the host address (1-254).
Subnet-mask should be: 255.255.255.0
Network Address should be: 192.168.0.0
Broadcast Address should be: 192.168.0.255
Valid Hosts (Host range) should be: 192.168.0.1 — 192.168.0.254
Working for Host range:
2^8 — 2 –> 256 — 2 = 254
/24 : is called as “slash notation”. It’s the number of bits that are specified. An IPv4 adress is 32 bits, divided up into 4 groups of 8 bits (n umbers from 0 to 255). 192.168.1.0/24 means any IP address in the range of 192.168.1.0 to 192.168.1.255. An IP address of 192.168.2.0/23 would be any IP address in the range 192.168.2.0 to 192.168.3.255 (notice the third number changes too) because it can have any value in the last 9 bits.
Also see the subnet calculation
External (public) IP address¶
External IP address is routable IP address. This address is assigned to you by your ISP . ISP has to assigned IP address to you from public addresses range which was assigned to your ISP by IANA (Internet Assigned Numbers Authority).
IANA –> public addresses range –> ISP –> your external IP address
External IP address is used when you communicate with Internet.
You can notice that your External IP address change during the time. It is normal process because most of ISP gives you dynamic IP address. It means your ISP can change your External IP address how they need it. When you communicate with your devices from outside as a remote is good habit to have only one IP address without any change. For this purpose you need to get static IP address which is in most cases something extra and you have to pay for this service to your ISP .
Make from private IP address the public is done via NAT (Network Address Translation)
IP lookup, how to find your address
On both Windows and Mac, with or without a terminal
![]()
so you want to find your IP address for one reason or another. I will walk you through two ways of checking your IP address on both Windows and Mac but first let’s cover some basics. IP(Internet protocol) is a set of conventions we use when connecting multiple devices together. An IP address is the way that machines identify devices on a network. There are also private and public IP addresses. Private would be the IP address assigned to your computer ( or mobile, tablet, smart device, ext…) by the networking device(most often a router) in your home. This address is only used to identify that device on a specific network. The public address is the IP address of your network device assigned to your home network by your ISP(Internet service provider). When you request to visit a website the public address of your network is sent along with that request so the server knows where to send the files. It is then the networking device’s job to send those files to the correct device on the network.
Graphic Interface(easy)
Windows
Open the control panel through the start menu (search control panel if you can’t locate it). Under ‘network and internet’ click ‘view network status and tasks’. Click the name of your network connection (most likely WIFI or ethernet) this will open a new window. Below some of the information you should find a details button click that. Among the info listed you should find an IPv4 address, this is your private IP, and the public address is listed as IPv4 default gateway.
Mac OS
Click the apple logo and open system preferences. Then go to the Network option. Depending on if you’re connected by WIFI or ethernet you will have to select that type of connection on the left hand side (one will have a green selection display that is the way you are connected with). Once clicked the connection type will display an IP address on the upper right hand side this is your private IP address of the machine you are using. To find the public address click advanced in the bottom right then select the TCP/IP tab along the top. Among the information displayed should be your router’s IP labeled router.
With a Terminal (advanced)
Windows
Open the command prompt or PowerShell and run the following command.
This will display a fair amount of information. You will be looking for the line that says default gateway under network adapter. That’s your router’s ip address (public). If you wish to find your computer’s ip (private) it will be labeled ipv4 address.
Open the terminal and then the command you run will vary based on if you are connected via WIFI or ethernet. For ethernet run
And for wifi run
Note that these commands will display your local IP for the machine you run these commands on. The public IP address for your network is that of your router. Which you can find by running the following command
Safety tip
Now you know how easy it is to find your IP address. The unfortunate part is that others can find it as well. Remember earlier I mentioned how when you request to visit a website your public IP is sent along with that request. This is how advertisers know to show you ads for the shop down the street and not one on the other side of the country. It is also how hackers can find your network. Using a VPN service to keep your IP hidden. Protecting you from potential online threats. Nothing is foolproof and there is always a level of risk when using the internet but VPNs can really help keep you safe.
Как получить свой публичный IP-адрес в сценарии Linux Bash

Резюме: вы можете получить свой внешний IP-адрес с веб-сайта с помощью команды curl, например «curl -s ifconfig.me». Однако веб-сайты могут меняться. Чтобы получить более надежный ответ, используйте команду dig, например dig @resolver1.opendns.com myip.opendns.com +short, чтобы получить свой IP-адрес с DNS-сервера.
Вам понадобится ваш внешний IP-адрес, если вы хотите удаленно подключиться к вашему компьютеру. Найти его вручную легко, но вот как найти его из скрипта Linux.
Внутренние и внешние IP-адреса
Адреса интернет-протокола используются для идентификации устройств в сети. Это уникальная метка в сети, назначенная одному устройству. Если другое устройство хочет отправить данные на это устройство, оно может сделать это, используя свой IP-адрес.
В ваш широкополосный модем встроен сетевой маршрутизатор, который направляет сетевой трафик по сети от одного устройства к другому. Это также местный орган власти, который выделяет IP-адреса устройствам, когда они присоединяются к сети. Он также поддерживает таблицу сетевых имен и IP-адресов. Это позволяет вам давать осмысленные имена компьютерам в вашей сети, потому что людям легче работать с именами, чем со списками номеров.
Устройства в интернете также имеют IP-адрес. У некоторых из них тоже есть имена, например, веб-сайты. Поставщики услуг доменных имен автоматически ищут доменные имена веб-сайтов и обменивают их на IP-адреса.
Ваш широкополосный модем получает собственный внешний IP-адрес с выходом в Интернет от поставщика услуг Интернета (ISP). Независимо от количества устройств, которые могут быть у вас дома, подключенных к Интернету, весь их общий трафик проходит через этот единственный IP-адрес.
Если вы находитесь за городом и хотите подключиться к службе, запущенной на одном из компьютеров в вашем доме, вам нужно будет использовать для этого свой внешний IP-адрес. Конечно, ваш маршрутизатор должен быть настроен для направления вашего запроса на подключение к соответствующему устройству в вашем доме.
Если вы ежемесячно не платите своему интернет-провайдеру за статический IP-адрес, ваш внешний IP-адрес может время от времени меняться. Перезагрузка вашего широкополосного модема вполне может привести к тому, что вы получите другой внешний IP-адрес. Поэтому, если вам нужно узнать свой внешний IP-адрес, вы не можете просто проверить его один раз и сохранить. Вам нужно будет периодически определять, что это такое.
Поиск вашего внешнего IP-адреса
Чтобы узнать свой внешний IP-адрес, нужно поговорить с чем-то, что находится за пределами вашей сети. Другими словами, доступ к чему-то в Интернете, который может дать нам нужную информацию. Нам нужно заглянуть в пустоту и увидеть, что смотрит на нас. А затем спросите у него наш внешний адрес.
Есть два способа сделать это. Один из способов связан с веб-сайтами. Есть много веб-сайтов, которые покажут вам, какой у вас внешний IP-адрес, а также кучу другой информации. Вы можете получить к ним доступ в своем браузере или использовать инструмент командной строки, такой как curl , который может выполнять HTTPS-запросы.
Другой способ — использовать специальную команду, например dig . Команда dig опрашивает DNS-серверы для получения информации.
Использование браузера
Конечно, использование браузера — не удобный способ получения внешнего IP-адреса. Но просмотр веб-сайта, предоставляющего эту услугу, может дать нам полезную информацию. Раньше мы рекомендовали ip4.me, но сайт не был обновлен до HTTPS. Он по-прежнему использует старый, небезопасный HTTP. Сайт все еще работает, но теперь есть лучшие альтернативы.
Сайт ifconfig.me предоставляет хороший набор информации.

Это сообщает о нашем внешнем IP-адресе как 178.238.11.140. Прокрутив веб-страницу вниз, вы найдете список команд, которые можно использовать для получения информации с сайта.

Все примеры, которые они приводят, используют curl для опроса сайта. Итак, давайте рассмотрим использование curl .
Использование завитка
На наших тестовых машинах в Fedora 37 уже был установлен curl . Нам нужно было установить его на наши компьютеры Ubuntu и Manjaro.
Чтобы установить его на Ubuntu, введите:

Команда на Манджаро:

Мы можем попробовать это с помощью первой команды, указанной на веб-странице ifconfig.me .

Наш внешний IP-адрес извлекается и отображается в окне терминала. Выход голые кости. После строки не печатается даже символ новой строки. Командная строка упирается в IP-адрес.
Эта команда работает, потому что возврат IP-адреса является действием веб-сайта по умолчанию. Если действие по умолчанию когда-либо изменится, мы можем получить другой результат. Чтобы удовлетворить это, мы можем указать, что запрашиваем наш IP-адрес, добавив идентификатор «ip» к URL-адресу.

Это возвращает IP-адрес, как и раньше.
Это иллюстрирует проблему использования веб-сайта в качестве источника вашего IP-адреса. Веб-сайты могут закрыться или изменить способ своей работы или формат возвращаемой информации. Эти изменения приведут к тому, что сценарии, зависящие от этих сайтов, будут либо сбоить, либо вести себя непредсказуемо.
Использование авторитетного и надежного ресурса, такого как DNS-сервер, является более надежным способом получения вашего внешнего IP-адреса. Чтобы запросить DNS-сервер, нам нужно использовать команду dig.
Использование команды копать
На этот раз dig был установлен на Fedora и Ubuntu, а нам нужно было установить его только на Manjaro.
Это обычная команда pacman , так что ничего удивительного, но имя пакета не такое, как вы могли ожидать.

Чтобы использовать dig для обнаружения нашего внешнего IP-адреса, нам нужно указать его на DNS-сервер. Мы используем сервер OpenDNS, предоставленный Cisco.
Нам нужно указать имя DNS-сервера, которое мы хотим использовать, перед которым ставится знак «@». Нам также нужно указать тип записи, которую мы хотим получить. В данном случае это «myip». Параметр +short гарантирует, что мы получим краткий, а не подробный ответ.

На этот раз после нашего IP-адреса напечатан символ новой строки. Как мы увидим, это печатается после строки IP-адреса и не является неотъемлемой частью самой строки.
Использование их в скрипте
Есть много причин, по которым вы можете захотеть узнать свой внешний IP-адрес из скрипта. Возможно, у вас есть скрипт, который отслеживает, изменился ли ваш внешний IP-адрес, и уведомляет вас, когда это происходит. Или, возможно, сервер уведомляет своих клиентов, когда его адрес меняется. Какими бы ни были ваши причины, мы можем довольно легко реализовать команды, которые мы использовали, в командной строке внутри скрипта.
Чтобы получить наш внешний IP-адрес и назначить его переменной, нам нужно только обернуть команду внутри подстановки команд, $ (. ) и назначить ее переменной, например :
Команда в круглых скобках выполняется, и возвращаемое значение заменяется выражением. В этом примере команда упрощена до «переменная=возвращаемое значение».
Вот это в сценарии. Мы добавили параметр -s (тихий) в команду curl , чтобы она не сообщала о ходе извлечения данных.
Скопируйте этот скрипт в редактор и сохраните его как «getex1.sh» и сделайте его исполняемым с помощью команды chmod .

Выполним скрипт и посмотрим, что у нас получится.

Чтобы сделать то же самое с более надежным вариантом использования DNS-сервера, а не веб-сайта, все, что нам нужно сделать, это заменить команду curl на команду dig .
Сохраните это как скрипт «getex2.sh» и сделайте его исполняемым с помощью chmod .

Давайте выполним этот скрипт.

Из вывода двух скриптов видно, что, несмотря на то, что команда dig печатает символ новой строки в командной строке, в скрипте нет новой строки, добавленной в переменную extaddr .
Стремитесь к надежности
Всегда безопаснее использовать признанный сервис с хорошей репутацией и предсказуемым форматом вывода, чем пользоваться «неофициальным» веб-сайтом. Как и все остальное в Интернете, внимательно посмотрите, от кого вы получаете информацию».