- How To Find My Public IP Address From Command Line On a Linux
- Explain IP addresses
- Use dig command for determining my public IP address:
- Get ip address from hostname in C with Linux sockets
- 1. gethostbyname
- 2. getaddrinfo
- 17 thoughts on “ Get ip address from hostname in C with Linux sockets ”
- Example Uses of the Linux Host Command
- Obtain IP address or hostname information from a Linux shell prompt
- The Host Command
- Get the IP Address for a Domain Name
- Get the Domain Name From an IP Address
- Return the SOA Details for a Domain
- Summary
- Команда dig в Linux
- Синтаксис команды dig
- Опции и флаги dig
- Примеры использования dig
- 1. Получение информации о домене
- 2. Получение определённой записи
- 3. Использование определённого DNS-сервера
- 4. Получение домена по IP
- Выводы
How To Find My Public IP Address From Command Line On a Linux
H ow do I find out my public IP address on the Linux and OS X Unix command line to use with my own bash shell script without using third party web site? Is there command-line option which will show my dynamic IP address on a Ubuntu or Fedora Linux?
There are many ways to find out your public IP address or wan (Wide Area Network) IP on a Linux or Unix-like operating systems such as FreeBSD, OpenBSD, NetBSD, Apple OS X, and others.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Linux, macOS, WSL or Unix-like OS |
Est. reading time | 2 mintues |
This page explain how to find out your own IP address using command line options on an Ubuntu, Debian, CentOS Linux, macOS/OS X and Unix bash shell.
Explain IP addresses
An IP is short for Internet Protocol. It is used to identify computers or mobile devices on the Internet. Each device connected to the Internet has an IP address. IP address can be used to personalize information.
Use dig command for determining my public IP address:
- Open the Terminal application on Linux or Unix.
- Type the following dig (domain information groper) command on a Linux, OS X, or Unix-like operating systems to see your own public IP address assigned by the ISP:
dig +short myip.opendns.com @resolver1.opendns.com - You can also type:
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com - You should see your IP address on screen. This is the fastest way to find out your IP address without using 3rd party site.
Fig.01: Use dig command to find your IP address
Источник
Get ip address from hostname in C with Linux sockets
Socket applications often need to convert hostnames like google.com to their corresponding ip address. This is done through dns requests.
The socket api in linux provides functions like gethostbyname and getaddrinfo that can be used to perform the dns requests and get the ip address.
1. gethostbyname
The first method uses the traditional gethostbyname function to retrieve information about a hostname/domain name.
Code
Compile and Run
2. getaddrinfo
The second method uses the getaddrinfo function to retrieve information about a hostname/domain name. The getaddrinfo supports ipv6 better.
Compile and Run
A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .
17 thoughts on “ Get ip address from hostname in C with Linux sockets ”
Explain the program
Thank you
anyone checking this code while running the output….
./a.out http://www.google.com
First of all, thanks for putting this tutorial up! I have used it as a basis for my next-gen code! Having stated that, let me show you how I have improved it.
Your getaddrinfo example continuously overwrites the “ip” C-string, until interating through the linked list is finished. Why not simply write to it once at end of the loop, if only getting the last entry is what you REALLY want, but that’s hardly useful! What you want is to make sure you’re using an IP that works!
“man getaddrinfo” from the terminal. On my OSX, it has nice example of iterating through the list and trying to test a socket connection for TCP. I have turned that example into usable code, integrated with your tutorial’s code:
For UDP you can do similar things by implementing a “test” msg for the server to receive and acknowledge with adaptive retransmission timeout.
Actually, having learned a little more, I’ve reverted to the newer inet_ntop. Simpler to use, I’m unsure if any power is lost from using it. I think it will be alright. Just thought I would leave evidence of my trail.
I noticed the same problem. I used a similar fix. If I did the example with http://www.google.com, the original code, printed “0.0.0.0”. It appears the last entry given by default name server is broken. The first entry is correct.
Thanks very much, while getaddinfo is not always work:
Источник
Example Uses of the Linux Host Command
Obtain IP address or hostname information from a Linux shell prompt
The Linux host command finds the IP address for a domain and vice versa.
The Host Command
On its own, the host command returns a list of the possible switches that can be used with it.
To get the list, type the following in a terminal window:
The following results are displayed:
- -a is equivalent to -v -t ANY.
- -c specifies the query class for non-IN data.
- -C compares SOA records on authoritative nameservers.
- -d is equivalent to -v.
- -l lists all hosts in a domain, using AXFR.
- -i performs an IP6.INT reverse lookup.
- -N changes the number of dots allowed before root lookup is done.
- -r disables recursive processing.
- -R specifies the number of retries for UDP packets.
- -s stipulates that a SERVFAIL response should stop the query.
- -t specifies the query type.
- -T enables TCP/IP mode.
- -v enables verbose output.
- -w specifies to wait forever for a reply.
- -W specifies how long to wait for a reply.
- -4 uses IPv4 query transport only.
- -6 uses IPv6 query transport only.
- -m sets the memory debugging flag.
- -V prints the version number and exits.
Get the IP Address for a Domain Name
To return the IP address for a domain name, type the following command:
For example, to find the domain name for linux.lifewire.com, type the following command.
The results from the host command are as follows:
As shown, linux.lifewire.com is a subdomain for lifewire.com. Running the host command against the full lifewire.com domain name returns a different IP address.
There is some further output from the host command against lifewire.com, as it displays how mail is handled.
Be careful about investing too much in these results. Eagle eyes will note the discrepancy between the text of this article and the screenshot in this section. The latter was taken several months after the former had been previously reviewed. In that time, Lifewire’s servers migrated to a content delivery network such that the IP addresses appear to have changed when the mechanism of content delivery changed.
Get the Domain Name From an IP Address
The opposite of returning the IP address from a domain name is returning the domain name from an IP address.
You can do this by typing the following into a terminal window:
For example, 207.241.148.80 is the IP address for Lifewire.com. Type the following into a terminal window:
The results are as follows:
The host command, by default, returns enough information. However, you can get a more detailed output by using either the -d or -v switch as follows:
The results from the above command show the domain that was looked up along with any results. It also returns the SOA details for a domain.
Return the SOA Details for a Domain
SOA stands for Start of Authority. If you register a domain name and then host that domain with a web hosting company, the web hosting company must maintain an SOA for that domain. It provides a way of keeping track of domain names.
You can find the SOA details for a domain by typing the following command:
For example, type the following into a terminal window:
There are a number of results returned but each contains the same fields which are as follows:
- The primary name server.
- The responsible party for the domain.
- A timestamp, which changes when the domain is updated.
- The number of seconds before the zone should be refreshed.
- The number of seconds before a failed refresh should be retried.
- The upper limit in seconds before a zone is no longer considered authoritative.
- The negative result TTL.
Summary
There are other switches, such as -l, which provides a listing, and -T, which searches using TCP/IP instead of UDP.
You will find that many web servers refuse these types of queries.
In general, you will probably only need to use the host command to return either the IP address for a domain name or the domain name for an IP address.
Источник
Команда dig в Linux
Команда dig (domain information groper) — многофункциональный инструмент для опроса DNS-серверов. Она позволяет получить больше информации о конкретном домене, для того чтобы, например, узнать используемые им IP-адреса.
Этот инструмент может оказаться полезным сетевым администраторам для выявления неисправностей DNS. Аналоги чаще всего предлагают меньше функций и возможностей, чем может предоставить утилита командной строки dig. В этой статье мы рассмотрим что из себя представляет команда dig Linux, а также как ею пользоваться.
Синтаксис команды dig
Использовать команду dig несложно. Достаточно ввести название сервера, имя домена и передать команде подходящие опции:
$ dig @сервер доменное.имя тип записи флаги
- @cервер — IP-адрес или доменное имя DNS-сервера (если не указано, dig будет обращаться к DNS-серверу, используемому по умолчанию);
- доменное.имя — доменное имя интернет-ресурса, о котором необходимо получить информацию;
- тип записи — позволяет указать, для какого типа записи необходим вывод, например A, NS, MX или TXT;
- флаги — с помощью флагов утилите dig отдаются дополнительные команды; оговаривается, каким должен быть вывод команды (что в нём должно быть, а чего нет).
Опции и флаги dig
Во время работы утилиты dig могут использоваться следующие флаги:
- +[no]all — отображает или скрывает все установленные по умолчанию флаги отображения;
- +[no]answer — отображает только ответ на запрос;
- +[no]fail — эта опция указывает, должна ли утилита переключаться на следующий DNS сервер, если текущий не отвечает (по умолчанию стоит +fail);
- +short — сокращает вывод утилиты;
- +[no]cmd — отключает вывод заголовка и информации об использованных опциях утилиты;
- +[no]identify — используется вместе с флагом +short и отображает информацию об IP-адресе сервера;
- +[no]comments — удаляет все комментарии из вывода утилиты;
- +[no]trace — позволяет вывести список DNS серверов через которые прошёл запрос на получение информации о домене, по умолчанию отключено.
Вместе с dig можно применять следующие опции:
- -4 — позволяет использовать только IPv4;
- -6 — позволяет использовать только IPv6;
- -x — предназначена для получения домена по IP;
- -f — используется для чтения списка доменов из файла;
- -b IP-адрес — позволяет указать исходящий IP-адрес, с которого отправлен запрос к DNS-серверу, полезно, если к компьютеру подключено несколько сетевых карт;
- -r — предотвращает чтение настроек из файла
/.digrc;
Здесь указаны лишь некоторые флаги и опции. Если необходимо узнать больше, используйте команду:
Примеры использования dig
1. Получение информации о домене
Для того чтобы получить информацию о домене необходимо передать имя домена команде. Например, для google.com:
Рассмотрим каждую секцию вывода подробнее:
- HEADER — отображает информацию о версии утилиты, ID запроса, полученных ошибках и использованных флагах вывода. Выводится и другая важная информация о количестве запросов, обращений к DNS-серверу и т. д.;
- QUESTION SECTION — секция, которая отображает текущий запрос;
- ANSWER SECTION — секция, в которой отображается результат обработки созданного запроса (в данном случае это IP-адрес домена).
По умолчанию утилита выводит много лишней информации. Для получения только основных данных используйте запрос с флагом +short. Например:
dig google.com +short
Если использовать команду dig вместе с +noall, вы ничего не увидите, поскольку этот флаг отключает вывод всех секций.
dig google.com +noall
Если вместе с флагом +noall использовать флаг +answer, dig выведет только ту информацию, которая есть в секции ANSWER (IP-адрес, тип записи и пр.).
dig доменное.имя +noall +answer
Для создания комбинированного запроса можно использовать текстовый файл со списком сайтов, например, sites.txt. Чтобы создать текстовый документ с таким именем, введите следующую команду в терминале:
В файл необходимо добавить список доменов, для которых необходимо получить данные, например:
google.com
ya.ru
losst.ru
Для того чтобы получить информацию о перечисленных в файле sites.txt доменах, используйте команду:
dig -f sites.txt +noall +answer
2. Получение определённой записи
Согласно синтаксису команды dig linux, тип записи указывается после доменного имени. Для того чтобы получить MX-запись домена google.com, используйте команду:
dig google.com MX +noall +answer
Чтобы получить NS-запись для домена, введите в терминале такую команду:
dig google.com NS +noall +answer
Запрос записи A происходит по умолчанию. Однако мы можем прописать этот запрос отдельно, чтобы обеспечить её вывод без дополнительной информации:
dig google.com A +noall +answer
Для вывода записи TXT аналогичным образом используйте команду вида:
dig google.com TXT +noall +answer
Для просмотра всех типов записей одновременно используйте запрос вида:
dig google.com ANY +noall +answer
3. Использование определённого DNS-сервера
Если DNS-сервер не был указан, как это было показано в предыдущих примерах, утилита dig linux будет по очереди пробовать все серверы из файла /etc/resolv.conf. Если же и там ничего нет, dig отправит запрос на localhost.
Указывать DNS-серверы можно в формате IPv4 или IPv6. Это не имеет значения и не повлияет на вывод dig. Отправим запрос на публичный DNS-сервер Google. Его IP-адрес: 8.8.8.8. В этом случае запрос в dig будет выглядеть следующим образом:
dig @8.8.8.8 google.com +noall +answer
Как видно, для домена google.com используется IP-адрес: 142.250.75.14.
4. Получение домена по IP
Для того чтобы узнать имя домена с помощью команды dig по IP, используйте опцию -x. Например, для того, чтобы узнать домен, привязанный к IP адресу 87.250.250.242 выполните такую команду:
dig -x 87.250.250.242
Как видите, это IP адрес яндекса. Правда такой способ получения доменов работает не всегда. Если к IP привязано несколько доменов программа может вывести только первый. Для того чтобы сократить вывод и оставить только нужную нам информацию, можно ввести запрос следующим образом:
dig -x 87.250.250.242 +short
Команда отображает информацию о том, что это google.com. Как видите команда dig Linux способна на многое.
Выводы
В этой небольшой статье мы рассмотрели, как можно использовать dig для опроса DNS-серверов. Несмотря на то что команда достаточно простая, она позволяет получить много полезной информации. А чем вы пользуетесь для обращения к серверам DNS? Напишите об этом в комментариях ниже.
Источник