服务器:
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:fhb Version:0.1 Date:
Description:
Funcion List:
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int listenfd,connfd;
int n;
int i;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
char mesg[1000];
listenfd = socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(32000);
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
while(1)
{
bzero(&cliaddr,sizeof(cliaddr));
int cliaddrlen = sizeof(struct sockaddr);
recvfrom(listenfd,mesg,sizeof(mesg),0,(struct sockaddr*)&cliaddr,&cliaddrlen);
printf("**************************************\n");
printf("%s\n",mesg);
printf("**************************************\n");
sendto(listenfd,mesg,sizeof(mesg),0,(struct sockaddr *)&cliaddr,cliaddrlen);
}
close(listenfd);
return 0;
}
客户端:
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:fhb Version:0.1 Date:
Description:
Funcion List:
*****************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
int main(int argc,char **argv)
{
int sockfd;
int n;
struct sockaddr_in servaddr,cliaddr;
char sendline[1000];
char recvline[1000];
if(argc != 2)
{
printf("please input something!\n");
exit(0);
}
sockfd = socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
servaddr.sin_port = htons(32000);
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
while(fgets(sendline,1000,stdin)!=NULL)
{
sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr *)&servaddr,sizeof(servaddr));
n = recvfrom(sockfd,recvline,1000,0,NULL,NULL);
recvline[n] = '\0';
fputs(recvline,stdout);
}
return 0;
}