Linux网络编程之一个简单的时间获取客户程序

DAYTIME协议是基于TCP的应用,是一种有用的调试工具,它的作用是返回当前时间和日期,格式是字符串格式。DAYTIME服务器在TCP端口13侦听,一旦有连接建立就返回ASCII形式的日期和时间,在传送完后关闭连接。

DAYTIME服务也可以使用UDP协议,它的端口也是13,不过UDP是用数据报传送当前时间的。不管是TCP还是UDP,DAYTIME服务器接收到的数据都被忽略。

一、 实现源码

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define MAXLINE 4096

int main(int argc, char **argv)
{
	struct sockaddr_in servaddr;
	struct hostent *host = NULL;
	int sockfd, n, port;
	char recvline[MAXLINE+1];

	if(argc !=2 && argc != 3) {
		printf("USAGE:\t%s IP|Domain [PORT]\n", argv[0]);
		return 1;
	}

	// 输入没有端口号,用默认端口13
	if(argc == 2) {
		port = 13;
	}

	// 输入有端口号
	if(argc == 3) {
		port = atoi(argv[2]);
	}

	// 输入为IP地址
	inet_aton(argv[1], &servaddr.sin_addr);
	host = gethostbyaddr((void *)&servaddr.sin_addr, 4, AF_INET);

	// 输入为域名
	if(host == NULL) {
		host = gethostbyname(argv[1]);
	}

	// 输入有误
	if(host == NULL) {
		printf("Input Data Error !\n");
		return 1;
	}

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr = *(struct in_addr *)host->h_addr;

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printf("socket error !\n");
		return 1;
	}

	if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) <0) {
		printf("connect error !\n");
		return 1;
	}

	while((n = read(sockfd, recvline, MAXLINE)) > 0) {
		recvline[n] = '\0';
		printf("%s", recvline);
	}
	if(n < 0) {
		printf("read errror !\n");
		return 1;
	}

	printf("\n");
	close(sockfd);

	return 0;
}

二、 运行结果

[ycxie@fedora Workspace]$ ./daytimetcpclient time.nist.gov 13
58067 17-11-10 21:44:09 00 0 0 286.0 UTC(NIST) *

[ycxie@fedora Workspace]$ ./daytimetcpclient time.nist.gov
58067 17-11-10 21:49:48 00 0 0 742.9 UTC(NIST) *

[ycxie@fedora Workspace]$ ./daytimetcpclient 132.163.96.2
58067 17-11-10 22:05:02 00 0 0 705.5 UTC(NIST) *

Leave a Reply

Your email address will not be published. Required fields are marked *