客户端代码:
/*************************************************************************
> File Name: client.c
> Author: ma6174
> Mail: ma6174@163.com
> Created Time: 2020年07月22日 星期三 20时56分16秒
************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define N 128
int main(int argc, char const *argv[])
{
if(argc < 3)
{
fprintf(stderr,"input error\n");
exit(1);
}
int sockfd;
char buf[N];
//创建套接字
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
{
perror("fail to Create socket\n");
exit(1);
}
//设置地址结构
struct sockaddr_in clientaddr;
clientaddr.sin_family = AF_INET;
clientaddr.sin_addr.s_addr = inet_addr(argv[1]);
clientaddr.sin_port = htons(atoi(argv[2]));
char recv_buf[N]; //接收服务器发来的数据
socklen_t recv_len = sizeof(clientaddr);
while(1)
{
memset(buf,'\0',sizeof(buf));
memset(recv_buf,'\0',sizeof(recv_buf));
fgets(buf,N,stdin);
int len = strlen(buf);
if(sendto(sockfd,buf,N,0,(struct sockaddr *)&clientaddr,sizeof(clientaddr)) == -1)
{
perror("fail to sendto\n");
exit(1);
}
if(recvfrom(sockfd,recv_buf,N,0,(struct sockaddr*)&clientaddr,&recv_len)== -1)
{
perror("fail to accept serve data\n");
exit(1);
}
printf("from serve data is :%s\n",recv_buf);
if(memcmp(buf,"###",3) == 0) break;
}
close(sockfd);
return 0;
}
服务端代码:
/*************************************************************************
> File Name: serve.c
> Author: ma6174
> Mail: ma6174@163.com
> Created Time: 2020年07月22日 星期三 20时56分33秒
************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define N 128
int main(int argc, char const *argv[])
{
if(argc < 3)
{
fprintf(stderr,"input error\n");
exit(1);
}
int sockfd;
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
{
perror("fail to socket\n");
exit(1);
}
struct sockaddr_in serveaddr;
serveaddr.sin_family = AF_INET;
serveaddr.sin_addr.s_addr = inet_addr(argv[1]);
serveaddr.sin_port = htons(atoi(argv[2]));
socklen_t len = sizeof(serveaddr);
//bind
if(bind(sockfd,(struct sockaddr *)&serveaddr,len) == -1)
{
perror("fail to bind\n");
exit(1);
}
char buf[N];
while(1)
{
memset(buf,'\0',sizeof(buf));
if(recvfrom(sockfd,buf,N,0,(struct sockaddr*)&serveaddr,&len) == -1)
{
perror("fail to recvfrom\n");
exit(1);
}
printf("[ip : %s -- port : %d] data : %s\n",inet_ntoa(serveaddr.sin_addr),ntohs(serveaddr.sin_port),buf);
// strcat(buf,"*--*"); //
if(sendto(sockfd,"Accepted",N,0,(struct sockaddr*)&serveaddr,len) == -1)
{
perror("fail to sendto\n");
exit(1);
}
if(memcmp(buf,"###",3) == 0) //退出标志
break;
}
close(sockfd);
return 0;
}
测试结果:也可以多开几个客户端