我正在尝试学习套接字编程的基础知识,并且正在使用我发现的指南中的一些代码但是我遇到了编译错误。代码和错误如下所示
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#define PORT "21467"
int main(void)
{
int status;
struct addrinfo hints;
struct addrinfo *servinfo; // will point to the results
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
if ((status = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
//fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
// servinfo now points to a linked list of 1 or more struct addrinfos
// ... do everything until you don't need servinfo anymore ....
freeaddrinfo(servinfo); // free the linked-list
return 0;
}
编译错误:
server.c: In function 'main':
server.c:16: warning: incompatible implicit declaration of built-in function 'memset'
server.c:24: warning: incompatible implicit declaration of built-in function 'exit'
Undefined first referenced
symbol in file
getaddrinfo /var/tmp//ccU0yRDe.o
freeaddrinfo /var/tmp//ccU0yRDe.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
非常感谢任何帮助!
答案 0 :(得分:3)
如果您执行man memset
,则会看到手册页显示#include <string.h>
是必需的。把它放在文件的顶部。对exit
修改强>
需要-lnsl -lsocket
进行链接(假设是linux)