2010-05-30 33 views
0

这是一个从here,但无法在编译时:运行此代码段需要哪些头文件?

int main(int argc, char **argv) 
{ 
    struct hostent { 
     char *h_name; // main name 
     char **h_aliases; // alternative names (aliases) 
     int h_addrtype; // address type (usually AF_INET) 
     int h_length; // length of address (in octets) 
     char **h_addr_list; // alternate addresses (in Network Byte Order) 
    }; 
    #define h_addr h_addr_list[0] // First address of h_addr_list. 


    struct hostent *info_stackoverflow; 
    int i = 0; 
    info_stackoverflow = gethostbyname("www.stackoverflow.com"); 
    printf("The IP address of %s is %s", 
      info_stackoverflow->h_name, 
      inet_ntoa(* ((struct in_addr *)info_stackoverflow->h_addr))); 
    /* aliases */ 
    while(*(pc_ip->h_aliases + i) != NULL) 
    { 
     printf("\n\tAlias: %s", *(pc_ip->h_aliases + i)); 
     i++; 
    } 
} 

回答

0
#include <stdio.h> 
#include <winsock.h> 

虽然struct hostent已经被定义Winsock的,所以你会想从你的代码片段删除的hostent定义。

正如dmazzoni所指出的,pc_ip未在该代码中声明。它的使用方式类似于指向hostent结构的指针,因此您可以用info_stackoverflow代替pc_ip

当您链接时,您需要链接到ws2_32.lib。在运行时,您可能会遇到问题,直到您在代码的开始处添加对WSAStartup的呼叫,并且在从main返回之前在末尾添加WSACleanup

+0

你能弄清楚'pc_ip'是如何定义的吗? – httpinterpret 2010-05-30 06:26:23

+0

哦,在用info_stackoverflow替换pc_ip后,我在链接时出错:'error LNK2019:无法解析的外部符号_inet_ntoa @ 4参考' – httpinterpret 2010-05-30 06:32:46

+0

现在编译好了,但是在此行获得访问冲突'inet_ntoa(*((struct in_addr *)info_stackoverflow-> h_addr)));' – httpinterpret 2010-05-30 06:44:12

0

你需要这三个头:

#include <stdio.h> 
#include <netdb.h> 
#include <arpa/inet.h> 

你应该摆脱自己的结构hostent的定义。它已经在netdb.h中为你定义了,你的定义将会发生冲突。

提示:几乎在任何Unix系统上都可以试试“man gethostbyname”;大多数C函数的手册页会告诉你要包含哪些头文件。

这仍然不会编译,因为pc_ip是未定义的。我想你缺少部分代码段。

+0

什么库也是必要的? – httpinterpret 2010-05-30 06:33:29

+0

无,这些函数在标准C库中。 – dmazzoni 2010-05-30 18:04:14