UDP服务器代码
ucp_ser.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#define SER_PORT 5001
#define SER_ADDR "192.168.11.128"
#define BUFSIZE 1024
#define QUIT_STR "QUIT"
void main()
{
int sockfd;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd < 0)
{
perror("sockfd");
exit(1);
}
int b_reuser=-1;
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&b_reuser,sizeof(int));
struct sockaddr_in myaddr;
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(SER_PORT);
myaddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr));
char buf[BUFSIZE];
struct sockaddr_in recaddr;
socklen_t addrlen=sizeof(recaddr);
while(1)
{
bzero(buf,BUFSIZE);
if(recvfrom(sockfd,buf,BUFSIZE-1,0,(struct sockaddr *)&recaddr,&addrlen)<0)
{
perror("recvfrom");
exit(1);
}
char ipv4_addr[16];
if(!inet_ntop(AF_INET,(void *)&recaddr.sin_addr,ipv4_addr,sizeof(recaddr)))
{
perror("inet_ntop");
exit(1);
}
printf("receive from(%s,%d),data:%s\n",ipv4_addr,htons(recaddr.sin_port),buf);
if(!strncasecmp(buf,QUIT_STR,strlen(QUIT_STR)))
{
printf("client(%s,%d),is exiting\n",ipv4_addr,htons(recaddr.sin_port));
exit(1);
}
}
}
UDP客服端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#define QUIT_STR "QUIT"
#define BUFSIZE 1024
void main(int arc,char **arg)
{
if(arc != 3)
{
exit(1);
}
int sockfd;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
int port;
port=atoi(arg[2]);
struct sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
addr.sin_addr.s_addr=inet_addr(arg[1]);
char buf[BUFSIZE];
while(1)
{
if(fgets(buf,BUFSIZE-1,stdin)==NULL)
{
perror("fgets");
exit(1);
}
sendto(sockfd,buf,strlen(buf),0,(struct sockaddr *)&addr,sizeof(addr));
if(!strncasecmp(buf,QUIT_STR,sizeof(QUIT_STR)))
{
printf("client is exited\n");
exit(1);
}
}
}
结果
udp是无连接的,每次发送数据都要指定目的地址。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)