新手上路,刚刚学习了socket编程的,用UDP协议写了server端的代码如下,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <Winsock2.h>
void udps_respon(){
SOCKET sockfd;
int ret;
int addrlen;
char seraddr[100];
struct sockaddr_in udpaddr;
addrlen=sizeof(struct sockaddr_in);
while(1){
ret=recvfrom(sockfd,seraddr,sizeof(seraddr),0,(SOCKADDR*)&udpaddr,&addrlen);
if(ret==-1){
printf("recvfrom()failed:%s\n");
}
else{
printf("message:%s",seraddr);
}
sendto(sockfd,seraddr,sizeof(seraddr),0,(SOCKADDR*)&udpaddr,addrlen);
}
close(sockfd);
}
void main(){
SOCKET sockfd;
int addrlen;
int serverport = 1111;
int PASCAL WSAStartup(WORD wVersionRequested,LPWSADATA lpWSAData);
WORD wVersionRequested;
WSADATA wsaData;
LPWSADATA lpWSAData;
int err;
wVersionRequested=MAKEWORD(1,1);//给版本信息赋值
err=WSAStartup(wVersionRequested,&wsaData);
if(err!=0){
printf("初始化socket1.1失败!");
return;//找不到合适的版本
}
if(LOBYTE(wsaData.wVersion)!=1||HIBYTE(wsaData.wVersion)!=1){
WSACleanup();
return;
}
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1){
printf("establish socket unsuccessful!\n");
return;
}
struct sockaddr_in {
short sin_family;//AF_INET
int sin_port ;//端口,网络字节顺序
struct in_addr sin_addr;//IP地址网络字节顺序
char sin_zero[8];//保留,空字节,设为0
}udpaddr;//服务器地址信息;
udpaddr.sin_family = AF_INET;
udpaddr.sin_port = htons(serverport);
udpaddr.sin_addr.s_addr = htonl(INADDR_ANY);
addrlen=sizeof(struct sockaddr_in);
if(bind(sockfd,(SOCKADDR*)&udpaddr,addrlen)==-1){
printf("bind socket unsuccessful!\n");
return ;
}
else{
printf("bind socket successful!\n");
}
udps_respon();
WSACleanup();
}
通过编译后报出如下错误:C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `recvfrom@24'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `sendto@24'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `WSAStartup@8'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `WSACleanup@0'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `socket@12'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `htons@4'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `htonl@4'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `bind@12'|
C:\Users\Administrator\Desktop\my\DDD.o:DDD.c|| undefined reference to `WSACleanup@0'|
||=== Build finished: 9 errors, 0 warnings (0 minutes, 0 seconds) ===|
实在是不明白是什么原因,望高手给予指点,跪谢!
编译器用的是codeblocks,