用udp协议实现echo服务器(即服务器把收到的内容发送回去)
服务器:socket->bind->(recvfrom->sendto)循环
客户端:socket->connect->(recvfrom->sendto)循环
Server.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define MAXLINE 50
typedef struct sockaddr SA;
int main(int argc,char **argv)
{
int sockfd;
socklen_t peerlen;
struct sockaddr_in myaddr,peeraddr;
char buf[MAXLINE];
if((sockfd=socket(PF_INET,SOCK_DGRAM,0))<0)
{
printf("fail to socket\n");
exit(-1);
}
bzero(&myaddr,sizeof(myaddr));
myaddr.sin_family=PF_INET;
myaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
myaddr.sin_port=htons(8888);
if(bind(sockfd,(SA *)&myaddr,sizeof(myaddr))<0)
{
printf("fail to bind\n");
exit(-1);
}
while(1)
{
peerlen=sizeof(peeraddr);
recvfrom(sockfd,buf,sizeof(buf),0,(SA *)&peeraddr,&peerlen);
printf("connection from %s,port %d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port));
sendto(sockfd,buf,sizeof(buf),0,(SA *)&peeraddr,sizeof(peeraddr));
}
return 0;
}
Client.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define MAXLINE 50
typedef struct sockaddr SA;
int main()
{
int sockfd,nbyte;
struct sockaddr_in servaddr;
char buf[MAXLINE]="hello Server";
if((sockfd=socket(PF_INET,SOCK_DGRAM,0))<0)
{
printf("fail to socket\n");
exit(-1);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family =PF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(8888);
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))<0)
{
printf("fail to connect\n");
exit(-1);
}
sendto(sockfd,buf,sizeof(buf),0,(SA *)&servaddr,sizeof(servaddr));
bzero(buf,sizeof(buf));
recvfrom(sockfd,buf,MAXLINE,0,NULL,NULL);
printf("recv from server:%s\n",buf);
return 0;
}