我是C语言中的套接字编程的初学者。我在本书中获得了代码,当我编译时,这些是未定义引用的错误。请给出改正的提示!谢谢!
代码:
#include <stdio.h>
#include <winsock.h>
#include <winsock2.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define RCVBUFSIZE 32
int main(int argc, char *argv[]){
int sock;
struct sockaddr_in echoServAddr;
unsigned short echoServPort;
char *servIP;
char *echoString;
char echoBuffer[RCVBUFSIZE];
unsigned int echoStringLen;
int bytesRcvd, totalBytesRcvd;
if(argc>3 || argc>4){
printf("Usage: %s <Server IP> <Echo Word> [<Echo Port>\n",argv[0]);
exit(1);
}
servIP=argv[1];
echoString=argv[2];
if(argc==4){
echoServPort=atoi(argv[3]);
}
else{
echoServPort=7;
}
if((sock=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
printf("socket() failed!");
}
memset(&echoServAddr,0,sizeof(echoServAddr));
echoServAddr.sin_family=AF_INET;
echoServAddr.sin_addr.s_addr=inet_addr(servIP);
echoServAddr.sin_port=htons(echoServPort);
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0){
printf("connect() failed!");
}
echoStringLen=strlen(echoString);
if(send(sock,echoString, echoStringLen,0)!=echoStringLen){
printf("send() send maximum bytes than expected");
}
totalBytesRcvd=0;
printf("Received");
while(totalBytesRcvd<echoStringLen){
if((bytesRcvd=recv(sock,echoBuffer,RCVBUFSIZE-1,0))<=0){
printf("recv() failed!");
}
totalBytesRcvd+=bytesRcvd;
echoBuffer[bytesRcvd]='\0';
printf(echoBuffer);
}
close(sock);
exit(1);
}
我收到的错误如下:
In function `main':
client.cpp:34: undefined reference to `_socket@12'
client.cpp:39: undefined reference to `_inet_addr@4'
client.cpp:40: undefined reference to `_htons@4'
client.cpp:41: undefined reference to `_connect@12'
client.cpp:45: undefined reference to `_send@16'
client.cpp:51: undefined reference to `_recv@16'
collect2.exe [Error] ld returned 1 exit status
答案 0 :(得分:3)
根据我的观察,您正在尝试使用MinGW构建Winsock应用程序。
默认情况下,MinGW不会自动链接Winsock库( Ws2_32.lib ),因此您需要使用 -l </ strong> flag以及库的名称。
gcc winsock.c -o winsock.exe -lws2_32
编辑:如果你是使用MinGW套件的IDE(Code :: Block,DevC ++等),你可以尝试找到可以手动添加编译器标志的选项,并添加 -lws2_32 < / strong>进入编译器标志
编辑:根据您上面的评论,所以您正在使用Dev-C ++ IDE,以下是如何在IDE中使用ws2_32.lib库的指南