我是套接字编程的新手。我写了我的第一个代码,它给出了一个链接器错误。我搜索了这个问题,但找不到解决方案。所以,我正在尝试堆栈交换。(第一次:-))
这是代码,我使用的是 Windows XP
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include<stdio.h>
#include<string.h>
#include<winsock2.h>
#include<Ws2tcpip.h>
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 46
#endif
int main(int argc, char *argv[])
{
WSADATA wsaData;
if(WSAStartup(MAKEWORD(1,1), &wsaData) != 0){
fprintf(stderr, "WSAStartup failed.\n");
return 1;
}
int status;
struct addrinfo hints;
struct addrinfo *res, *p;
char ipstr[INET6_ADDRSTRLEN];
if(argc != 2){
fprintf(stderr,"usage: Shows IP address of hostname.\n");
return 1;
}
memset(&hints, 0 , sizeof hints);
hints.ai_family = AF_UNSPEC;
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;
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";
}
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf("%s : %s\n",ipver, ipstr);
}
freeaddrinfo(res);
WSACleanup();
return 0;
}
我正在使用以下命令编译它:
gcc file.c "C:\Program Files\CodeBlocks\MinGW\lib\ws2_32.a" -o final.exe
它给出以下错误:
(.text+0x21d): undefined reference to 'inet_ntop'
collect2: ld returned 1 exit status
是的,我正在使用 beej 指南来学习套接字编程。如果您想向我推荐其他一些不错的教程或书籍,请继续。谢谢。