udp协议的时间服务器

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

const int maxline=4096;

char * sock_ntop(const struct sockaddr *sa, socklen_t salen) {
	char portstr[8];
	static char str[128];
	
	switch(sa->sa_family) {
	case AF_INET: {
		struct sockaddr_in * sin = (struct sockaddr_in *) sa;
		if(inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str)) == NULL) {
			return NULL;
		}
		if(ntohs(sin->sin_port) != 0) {
			snprintf(portstr, sizeof(portstr), ":%d", ntohs(sin->sin_port));
			strcat(str, portstr);
		}
		return str;
	}
	}
}

void dg_echo(int sockfd, struct sockaddr * pcliaddr, socklen_t clilen) {
	int n;
	socklen_t len;
	char mesg[maxline], errbuff[maxline];
	time_t ticks;

	for(;;) {
		memset(mesg, 0, sizeof(mesg));
		len=clilen;
		if((n=recvfrom(sockfd, mesg, maxline, 0, pcliaddr, &len))<0) {
			strerror_r(errno, errbuff, maxline);
			fprintf(stderr, "recvfrom error: %s\n", errbuff);
			exit(-1);
		}
		printf("recv mesg: %s\n", mesg);
		printf("request from %s\n", sock_ntop(pcliaddr, len));

		ticks = time(NULL);
		snprintf(mesg, sizeof(mesg), "%.24s\r\n", ctime(&ticks));

		if(sendto(sockfd, mesg, sizeof(mesg), 0, pcliaddr, len)<0) {
			strerror_r(errno, errbuff, maxline);
			fprintf(stderr, "sendto error: %s\n", errbuff);
			exit(-1);
		}
	}
}

int main(int argc, char **argv) {
	int sockfd;
	struct sockaddr_in servaddr, cliaddr;
	char errbuff[maxline];

	if((sockfd=socket(AF_INET, SOCK_DGRAM, 0))<0) {
		strerror_r(errno, errbuff, maxline);
		fprintf(stderr, "socket error: %s\n", errbuff);
		exit(-1);
	}
	
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(13);

	if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0) {
		strerror_r(errno, errbuff, maxline);
		fprintf(stderr, "bind error: %s\n", errbuff);
		exit(-1);
	}

	dg_echo(sockfd, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
	
	return 0;
}	

  

posted @ 2023-04-06 22:44  东宫得臣  阅读(32)  评论(0编辑  收藏  举报