//server端代码
#include <stdio.h>
//#include <linux/in.h>#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int fd,ret;
struct sockaddr_in addr = {0};
fd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == fd)
{
printf("error:%s\n",strerror(errno));
return fd;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(2000);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(fd,(struct sockaddr *)(&addr),sizeof(struct sockaddr));
if(-1 == ret)
{
printf("error:%s\n",strerror(errno));
return ret;
}
int yes = 1;
ret = setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes));
if(-1 == ret)
{
printf("error:%s\n",strerror(errno));
return ret;
}
ret = listen(fd,5);
if(-1 == ret)
{
printf("error:%s\n",strerror(errno));
return ret;
}
while(1)
{
socklen_t len = sizeof(addr);
int cd = accept(fd,(struct sockaddr*)(&addr),&len);
if(-1 == cd)
{
printf("error:%s\n",strerror(errno));
return cd;
}
printf("connected from %s:%d\n",inet_ntoa(addr.sin_addr),addr.sin_port);
char buf[100] = {0};
time_t t = time(NULL);
strcpy(buf,ctime(&t));
ret = send(cd,buf,strlen(buf),0);
if(-1 == ret)
{
printf("error:%s\n",strerror(errno));
return ret;
}
printf("size %d of %d sent\n",ret,strlen(buf));
close(cd);
}
}
//客户端代码
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int fd,ret;
struct sockaddr_in addr = {0};
struct in_addr x;
inet_aton("192.168.1.103",&x);
addr.sin_family = AF_INET;
addr.sin_addr = x;
addr.sin_port = htons(2000);
fd = socket(AF_INET,SOCK_STREAM,0);
if(fd == -1)
{
printf("error:%s\n",strerror(errno));
return fd;
}
ret = connect(fd,(sockaddr*)&addr,sizeof(addr));
if(ret == -1)
{
printf("error:%s\n",strerror(errno));
return fd;
}
char buf[100]={0};
ret = recv(fd,buf,sizeof(buf),0);
if(ret == -1)
{
printf("error:%s\n",strerror(errno));
return fd;
}
write(STDOUT_FILENO,buf,ret);
close(fd);
return 0;
}