C语言使用Windows Sockets API获取主机和域名IP地址
C语言使用Windows Sockets API获取主机和域名IP地址
本篇博客将介绍如何使用Windows Sockets API函数,用C语言编写代码来获取主机名、主机IP地址以及指定域名的IP地址。
以下是完整的代码示例:
#include <stdio.h>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
int main()
{
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0)
{
printf('Failed to initialize winsock. Error code: %d', result);
return 1;
}
// Step 2: 获取指定域名的IP地址
const char* domain = 'www.example.com'; // 将此处替换为目标域名
struct addrinfo* result_list = NULL;
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
result = getaddrinfo(domain, NULL, &hints, &result_list);
if (result != 0)
{
printf('Failed to get IP addresses for the given domain. Error code: %d', result);
WSACleanup();
return 1;
}
struct addrinfo* ptr = result_list;
int i = 1;
while (ptr != NULL)
{
printf('Domain IP Address %d: ', i);
if (ptr->ai_family == AF_INET)
{
struct sockaddr_in* ipv4 = (struct sockaddr_in*)ptr->ai_addr;
char ip_address[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(ipv4->sin_addr), ip_address, INET_ADDRSTRLEN);
printf('%s\n', ip_address);
}
else if (ptr->ai_family == AF_INET6)
{
struct sockaddr_in6* ipv6 = (struct sockaddr_in6*)ptr->ai_addr;
char ip_address[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(ipv6->sin6_addr), ip_address, INET6_ADDRSTRLEN);
printf('%s\n', ip_address);
}
ptr = ptr->ai_next;
i++;
}
freeaddrinfo(result_list);
printf('\n');
// Step 3: 获取主机名
char hostname[256];
result = gethostname(hostname, sizeof(hostname));
if (result != 0)
{
printf('Failed to get the hostname. Error code: %d', result);
WSACleanup();
return 1;
}
printf('Hostname: %s\n', hostname);
printf('\n');
// Step 4: 获取主机的IP地址
struct hostent* host_info;
host_info = gethostbyname(hostname);
if (host_info == NULL)
{
printf('Failed to get IP addresses for the current host.');
WSACleanup();
return 1;
}
i = 1;
while (host_info->h_addr_list[i - 1] != NULL)
{
struct in_addr* addr = (struct in_addr*)host_info->h_addr_list[i - 1];
printf('Host IP Address %d: %s\n', i, inet_ntoa(*addr));
i++;
}
WSACleanup();
return 0;
}
代码解析:
- 包含头文件: 包含必要的头文件,例如
stdio.h,windows.h,winsock2.h和ws2tcpip.h。 - 初始化Winsock: 调用
WSAStartup函数初始化 Windows Sockets 库。 - 获取指定域名的IP地址:
- 定义域名变量
domain并设置目标域名。 - 使用
getaddrinfo函数获取指定域名的IP地址信息,并将结果存储在result_list中。 - 遍历
result_list,使用inet_ntop函数将IP地址转换为字符串并打印。
- 定义域名变量
- 获取主机名:
- 使用
gethostname函数获取主机名,并将结果存储在hostname数组中。 - 打印主机名。
- 使用
- 获取主机的IP地址:
- 使用
gethostbyname函数获取主机的IP地址信息,并将结果存储在host_info中。 - 遍历
host_info中的IP地址列表,使用inet_ntoa函数将IP地址转换为字符串并打印。
- 使用
- 清理资源: 调用
WSACleanup函数清理 Windows Sockets 资源。
请注意:
- 以上代码需要在安装了 Windows Sockets 库的环境下运行。
- 你需要将代码中的
www.example.com替换成你想要获取IP地址的目标域名。
希望这篇博客能够帮助你理解如何使用C语言和Windows Sockets API获取主机和域名IP地址。
原文地址: https://www.cveoy.top/t/topic/ESi 著作权归作者所有。请勿转载和采集!