unix网络编程--时间同步

以下代码在centos6.2测试通过

客户端代码如下:

#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include <stdio.h>
#include <errno.h>

using namespace std;

#define MAXLINE     4096    /* max text line length */
int main(int argc, char ** argv)
{
	int sockfd, n;
	char recvline[MAXLINE+1];
	struct sockaddr_in serveraddr;
	if(argc != 2)
	{
		cout << "para error " << endl;
		return 0;
	}
	if((sockfd=socket(AF_INET, SOCK_STREAM, 0))<0)
	{
		cout << "socket error" << endl;
		return 0;
	}
	memset(&serveraddr,0, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(10000);
	if(inet_pton(AF_INET, argv[1], &serveraddr.sin_addr)<=0)
	{
		cout << "inet_pton error for " << argv[1] << endl;
		return 0;
	}
	int tmp = connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
	if(tmp <0)
	{
		cout << "connect error" << tmp << endl;
		cout << "error info " << errno << endl;
		return 0;
	}
	while((n=read(sockfd, recvline, MAXLINE)) > 0)
	{
		recvline[n] = 0;
		if(fputs(recvline, stdout) == EOF)
		{
			cout << "fputs error" << endl;
		}
	}
	if(n<0)
	{
		cout << "read error" << endl;
	}
	return 1;
}


 

 

服务器端代码如下:

 

 

#include <arpa/inet.h> // sockaddr head
#include <string.h>  //memset and strlen head
#include <sys/socket.h> //socket listen bind 
#include <iostream>
#include <time.h>
#include <stdio.h>

#define MAXLINE 4096
#define LISTENQ 1024

using namespace std;

int main(int argc, char ** argv)
{
	int listenfd, connfd;
	struct sockaddr_in servaddr;
	char buff[MAXLINE];
	time_t ticks;
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(10000);

	bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	int ret = listen(listenfd,LISTENQ);
	cout << "go to listen" <<ret<< endl;
	for(; ;)
	{
		connfd = accept(listenfd, (struct sockaddr *)NULL, NULL);
		cout << "connfd = " << connfd << endl;
		ticks = time(NULL);
		snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
		write(connfd, buff, strlen(buff));
		close(connfd);
	}

	return 0;
}


 

你可能感兴趣的:(unix网络编程--时间同步)