C语言获取主机名和IP地址:解决'inet_ntop'未声明错误

在Windows环境下使用C语言进行网络编程时,你可能会遇到使用inet_ntop函数时出现'inet_ntop'未声明的错误。这是因为inet_ntop函数在Windows平台上不可用。

为了解决这个问题,你可以使用inet_ntoa函数来代替inet_ntop函数转换IPv4地址。

以下是经过修改后的代码:c#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: Get IP addresses for a given domain    const char* domain = 'www.example.com'; // Replace with the desired domain    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_ntoa 替换 inet_ntop            inet_ntoa(ipv4->sin_addr);            printf('%s

', ip_address); } else if (ptr->ai_family == AF_INET6) { struct sockaddr_in6* ipv6 = (struct sockaddr_in6*)ptr->ai_addr; // TODO: Handle IPv6 addresses } ptr = ptr->ai_next; i++; } freeaddrinfo(result_list);

printf('

');

// Step 3: Get the hostname    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

', hostname);

printf('

');

// Step 4: Get IP addresses for the host    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;        memcpy(&addr, host_info->h_addr_list[i - 1], sizeof(struct in_addr));        printf('Host IP Address %d: %s

', i, inet_ntoa(addr)); i++; }

WSACleanup();    return 0;}

这个代码会在控制台输出当前主机名以及对应的IP地址,然后通过指定的域名获取相应的IP地址。请注意,以上代码假设你已经正确安装了Windows Sockets库,并且需要根据自己的需求进行适当的修改。

C语言获取主机名和IP地址:解决'inet_ntop'未声明错误

原文地址: https://www.cveoy.top/t/topic/EXy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录