Sure! Here is a step-by-step guide on how to implement obtaining the IP address of a domain in C/C++:
- Include the necessary header files:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
- Declare the main function:
int main() {
// Code goes here
return 0;
}
- Prompt the user to enter a domain name:
char domain[100];
printf(\"Enter a domain name: \");
scanf(\"%s\", domain);
- Use the
gethostbyname
function to retrieve the IP address:
struct hostent *host;
host = gethostbyname(domain);
- Check if the domain exists:
if (host == NULL) {
printf(\"Domain not found.\
\");
return 1;
}
- Convert the IP address to a string format:
char ip[100];
inet_ntop(AF_INET, host->h_addr_list[0], ip, sizeof(ip));
- Print the IP address:
printf(\"IP address: %s\
\", ip);
- Complete the main function:
int main() {
char domain[100];
printf(\"Enter a domain name: \");
scanf(\"%s\", domain);
struct hostent *host;
host = gethostbyname(domain);
if (host == NULL) {
printf(\"Domain not found.\
\");
return 1;
}
char ip[100];
inet_ntop(AF_INET, host->h_addr_list[0], ip, sizeof(ip));
printf(\"IP address: %s\
\", ip);
return 0;
}
Now, let's see two examples of how to use this code:
Example 1:
Enter a domain name: www.google.com
IP address: 172.217.168.196
Example 2:
Enter a domain name: www.openai.com
IP address: 104.16.249.35
Please note that this code only supports IPv4 addresses. If you want to support IPv6 addresses, you will need to modify the code accordingly.
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:c/c++实现获取域名的IP地址 - Python技术站