标签:
/************************************************************************* > File Name: getdate2.c > Description: getdate2.c > Author: Liubingbing > Created Time: 2015年07月26日 星期日 15时37分05秒 > Other: getdate2.c ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> int main(int argc, char *argv[]) { char *host; int sockfd; int len, result; struct sockaddr_in address; struct hostent *hostinfo; struct servent *servinfo; char buffer[128]; if (argc == 1) host = "localhost"; else host = argv[1]; /* 找到主机地址,如果没有找到则报错 */ hostinfo = gethostbyname(host); if (!hostinfo) { fprintf(stderr, "no host: %s\n", host); exit(1); } /* 检查主机上是否存在daytime服务 */ servinfo = getservbyname("daytime", "udp"); if (!servinfo) { fprintf(stderr, "no daytime service\n"); exit(1); } printf("daytime port is %d\n", ntohs(servinfo->s_port)); /* socket创建一个UDP套接字 */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); /* 创建地址 */ address.sin_family = AF_INET; address.sin_port = servinfo->s_port; address.sin_addr = *(struct in_addr *)*hostinfo->h_addr_list; len = sizeof(address); /* sendto(int sockfd, void *buffer, size_t len, int flags, struct sockaddr *, socklen_t tolen); * sendto系统调用从buffer缓存区中给使用指定套接字地址的目标服务器发送一个数据报 */ result = sendto(sockfd, buffer, 1, 0, (struct sockaddr *)&address, len); /* recvfrom(int sockfd, void *buffer, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen); * recvfrom系统调用在套接字上等待从特定地址到来的数据报,并将它放入buffer缓存区 */ result = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&address, &len); buffer[result] = '\0'; printf("read %d bytes: %s", result, buffer); close(sockfd); exit(0); }
int sendto(int sockfd, viod *buffer, size_t len, int flags, struct sockaddr *to, socklen_t tolen);在正常应用中,flags参数一般被设置为0.
int recvfrom(int sockfd, void *buffer, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen);同样,在正常应用中,flags参数一般被设置为0.
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/yiranant/article/details/47074661