本文为senlie原创,转载请保留此地址:
/** * UDP 协议无关 调用 getaddrinfo 和 udp_server **/#include "unp.h"#includeintmain(int argc, char **argv){ int sockfd; ssize_t n; char buff[MAXLINE]; time_t ticks; socklen_t len; struct sockaddr_storage cliaddr; //1.利用 Udp_server 得到套接字 if (argc == 2) sockfd = Udp_server(NULL, argv[1], NULL); else if (argc == 3) sockfd = Udp_server(argv[1], argv[2], NULL); else err_quit("usage: daytimeudpsrv [ ] "); //2.服务器循环。
接受客户请求。发送应答 for ( ; ; ) { len = sizeof(cliaddr); //服务器堵塞在 recvfrom 调用,等待客户连接 n = Recvfrom(sockfd, buff, MAXLINE, 0, (SA *)&cliaddr, &len); printf("datagram from %s\n", Sock_ntop((SA *)&cliaddr, len)); //发送应答 ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); Sendto(sockfd, buff, strlen(buff), 0, (SA *)&cliaddr, len); //没有连接,所以不用关闭已连接套接字 } }