0

我试图从 Beej 的网络指南编译一些示例代码,但我的编译器给了我错误“C:\Dev-Cpp\mainweq.cpp `inet_ntop' undeclared (first use this function)”,即使我包含了 ws2tcpip.h。这是代码:

/*
** showip.c -- show IP addresses for a host given on the command line
*/

#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include <Ws2tcpip.h>
WSADATA wsaData;

#pragma comment(lib, "Ws2_32.lib")

int iResult;


int main(int argc, char *argv[])
{
int iResult;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}

struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];

if (argc != 2) {
    fprintf(stderr,"usage: showip hostname\n");
    return 1;
}

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;

if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
    return 2;
}

printf("IP addresses for %s:\n\n", argv[1]);

for(p = res;p != NULL; p = p->ai_next) 
    {
    void *addr;
    char *ipver;

    // get the pointer to the address itself,
    // different fields in IPv4 and IPv6:
    if (p->ai_family == AF_INET) { // IPv4
        struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
        addr = &(ipv4->sin_addr);
        ipver = "IPv4";
    } 
    else 
    { // IPv6
        struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
        addr = &(ipv6->sin6_addr);
        ipver = "IPv6";
    }

    // convert the IP to a string and print it:
    inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
    printf("  %s: %s\n", ipver, ipstr);
}

freeaddrinfo(res); // free the linked list

return 0;
}
4

3 回答 3

0

您正在寻找 inet_ntoa 或 WSAAddressToString 或 InetNtop?

更多在这里

于 2012-12-11T13:32:54.417 回答
0

inet_ntop在 Vista 之前在 Windows 上不可用。如果您可以编写可移植代码,请避免使用特定于平台的函数。

在这里,使用getnameinfowithNI_NUMERICHOST和 no service,这完全等同于inet_ntop(但没有那么多讨厌的转换)。

可用性:所有 unix 和 Win2K+ 都有getnameinfo.

于 2012-12-11T14:31:45.343 回答
0

Beej 没有说包括ws2tcpip.h. 他说包括arpa/inet.h

但是inet_ntop是一个POSIX函数。更有可能的是,您正在寻找 Windows 等价物,例如WSAAddressToString.

于 2012-12-11T13:34:48.927 回答