#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 1234
#define MAXDATASIZE 100
int main()
{
int sockfd;
socklen_t client_len;
ssize_t recv_num,send_num;
struct sockaddr_in server;
struct sockaddr_in client;
char recv_buf[MAXDATASIZE];
char send_buf[MAXDATASIZE];
char response[MAXDATASIZE];
char wel_msg[]="[!] Welcome,I can return your input,you can input 'quit' to exit:)";
if((sockfd = socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket() failed.");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=htonl(INADDR_ANY);
client_len=sizeof(client);
if((bind(sockfd,(struct sockaddr *)&server,sizeof(server)))==-1)
{
perror("bind() failed.");
exit(1);
}
if((recvfrom(sockfd,response,MAXDATASIZE,0,(struct sockaddr *)&client,&client_len))==-1)
{
perror("recvfrom() failed.");
exit(1);
}
printf("[!] You got a connection: message <%s> client ip <%s> port <%d>\n",response,inet_ntoa(client.sin_addr),ntohs(client.sin_port));
if((sendto(sockfd,wel_msg,sizeof(wel_msg),0,(const struct sockaddr *)&client,client_len))==-1)
{
perror("sendto() failed");
exit(1);
}
while(1)
{
if((recv_num=recvfrom(sockfd,recv_buf,MAXDATASIZE,0,(struct sockaddr *)&client,&client_len))==-1)
{
perror("recvfrom() failed.");
exit(1);
}
recv_buf[recv_num]='\0';
printf("[>] Receive client inputed string:%s\n",recv_buf);
printf("[*] Return client inputed string:%s\n",recv_buf);
strcpy(send_buf,recv_buf);
if((send_num=(sendto(sockfd,send_buf,sizeof(send_buf),0,(struct sockaddr *)&client,client_len)))==-1)
{
perror("sendto() failed");
exit(1);
}
if(!strcmp(recv_buf,"quit"))
{
printf("[!] Client request to exit.\n");
close(sockfd);
exit(1);
}
}
close(sockfd);
return 0;
}