Makefile
all: server client
server:server.c
gcc -o $@ $^
client:client.c
gcc -o $@ $^
clean:
rm -rf server client
server.c
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#inclide <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
int main(int argc,char const* argv[]){
if(argc<2){
printf("Please input port\n");
exit(0);
}
//创建文件描述符
int sockfd=socket(AF_INET,SOCK_DGREAM,0);
if(sockfd<0){
perror("socket err");
exit(0);
}
//绑定服务器的地址
struct socaddr_in server;
server.sin_family=AF_INET;
server.port=htons(atoi(argv[1]));
server.sin_addr.s_addr=inet_addr("127.0.0.1");
socklen_t addrlen=sizeof(server);
if(bind(sockfd,(struct sockaddr *)&server,addrlen)<0){
perror("bind err");
exit(0);
}
#define N 64
char buf[N]={0};
struct sockaddr cliddr;
while(1){
recvfrom(sockfd,buf,N,&cliaddr,&addrlen);
printf("recv data=%s\n",buf);
sendto(sockfd,buf,N,0,&cliaddr,addrlen);
bzero(buf,N);
}
close(sockfd);
return 0;
}
client.c
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,const char * argv){
if(argc<2){
perror("please input port");
exit(-1);
}
int sockfd=socket(AF_INET,SOCK_DGREAM,0);
if(sockfd<0){
perror("sock err");
exit(-1);
}
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[1]));
server.sin_addr.s_addr("127.0.0.1");
socklen_t addrlen=sizeof(server);
#define N 32
char res[N]={"Hello world"};
sendto(sockfd,res,sizeof(res),0,(struct sockaddr *)&server,addrlen);
char rec[N]={0};
recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&server,addrlen);
printf("%s\n",rec);
close(sockfd);
return 0;
}