目的:C语言实现udp_client 和udp_server功能,实现简单的数据收发功能;
参考出处:
1、https://www.cnblogs.com/yuqiao/p/5786427.html //socket接口详解
2、https://blog.csdn.net/zgrjkflmkyc/article/details/8605333
文件需要包含<fcntl.h>以及<unistd.h>文件,否则编译时出现close()函数未定义warning。
测试UDP server:
测试UDP client:
/***************client.c***************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<errno.h>
#include<sys/types.h>
#include <fcntl.h>//for open
#include<unistd.h>//for close
int port=8888;int main(int argc,char *argv[]){
int sockfd;
int i=0;
int z;
char buf[80],str1[80];
struct hostent *host;
struct sockaddr_in adr_srvr;
if(argc<2){
fprintf(stderr,"please enter the server's hostname!\n");
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL){
herror("gethostbyname error!");
exit(1);
}
FILE *fp;
printf("open file....\n");
fp=fopen("liu","r");
if(fp==NULL){
perror("failed to open file");
exit(1);
}
printf("connecting server....\n");
adr_srvr.sin_family=AF_INET;
adr_srvr.sin_port=htons(port);
adr_srvr.sin_addr=*((struct in_addr *)host->h_addr);
bzero(&(adr_srvr.sin_zero),8);
sockfd=socket(AF_INET,SOCK_DGRAM,0);
// printf("socket %d\r\n",sockfd);
if(sockfd==-1){
perror("socket error!");
exit(1);
}
printf("send file ...\n");
for(i=0;i<3;i++){
fgets(str1,80,fp);
printf("%d:%s",i,str1);
sprintf(buf,"%d:%s",i,str1);
z=sendto(sockfd,buf,strlen(buf),0,(struct sockaddr *)&adr_srvr,sizeof(adr_srvr));
if(z<0){
perror("recvfrom error");
exit(1);
}
}
sprintf(buf,"stop\n");
z=sendto(sockfd,buf,strlen(buf),0,(struct sockaddr *)&adr_srvr,sizeof(adr_srvr));
printf("send over.\n");
if(z<0){
perror("sendto error");
exit(1);
}
fclose(fp);
close(sockfd);
exit(0);
}
/**************server.c**************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<errno.h>
#include<sys/types.h>
#include<fcntl.h>//for open
#include<unistd.h> //for close
int port=8888;
int main(){
int sockfd;
int len;
int z;
char buf[256];
struct sockaddr_in adr_inet;
struct sockaddr_in adr_clnt;
printf("waiting for client...\n");
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1){
perror("socket error_1");
exit(1);
}
printf("start bind..\n");
adr_inet.sin_family=AF_INET;
adr_inet.sin_port=htons(port);
adr_inet.sin_addr.s_addr=htonl(INADDR_ANY);
printf("bind para ok\n");
bzero(&(adr_inet.sin_zero),8);
len=sizeof(adr_clnt);
z=bind(sockfd,(struct sockaddr *)&adr_inet,sizeof(adr_inet));
if(z==-1){
perror("bind error_1");
}else{
printf("bind ok\n");
}
while(1){
// printf("before rec %s,",buf);
z=recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&adr_clnt, &len);
printf("rx data_len: %d \n", z);
if(z<0){
perror("recvfrom error_1");
exit(1);
}
buf[z]=0;
printf("接收:%s\n",buf);
if(strncmp(buf,"stop",4)==0){
printf("结束....\n");
break;
}
}
close(sockfd);
exit(0);
}