2012-02-26 93 views
1

我想了解套接字編程的基礎知識,並使用我發現的指南中的一些代碼,但我得到編譯錯誤。代碼和錯誤顯示如下用getaddrinfo編譯錯誤

#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

@Ryaan:如果您指定用來編譯命令和鏈接,版本這將是有益的你的工具和操作系統(我猜是OS X)。 – 2012-02-26 00:12:06

+1

我剛剛在一臺裝有gcc 4.6.1的Linux機器上試過,並在添加#include 和#include 後編譯成功,沒有任何警告。你使用的是什麼操作系統和編譯器? – jlemos 2012-02-26 00:14:59

+0

我在運行gcc 4.2.1的Unix上運行它。對不起,沒有。包括這兩個庫之後,我只有第一次引用的Undefined和下面給出的錯誤。 – Ryan 2012-02-26 02:27:59

回答

3

如果你做一個man memset,你會看到手冊頁說#include <string.h>是必需的。把它放在文件的頂部。用同樣的方法exit

編輯

極品-lnsl -lsocket的鏈接(假設Linux)的

+0

-lnsl -lsocket用於Solaris,其中套接字內容不在-lc中(*表示*爲Linux/glibc) – 2012-02-26 06:53:36

+0

您的權利。我讀了我擁有的Makefile的錯誤位。 – 2012-02-26 06:59:03

+0

得到它的工作!謝謝 – Ryan 2012-02-27 21:34:18