本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
/**
* UDP 协议无关 调用 getaddrinfo 和 udp_server
**/
#include"unp.h"
#include<time.h>
int
main(int argc, char **argv)
{
intsockfd;
ssize_tn;
charbuff[MAXLINE];
time_tticks;
socklen_tlen;
struct sockaddr_storagecliaddr;
//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 [ <host> ] <service or port>");
//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);
//没有连接,所以不用关闭已连接套接字
}
}