- 论坛徽章:
- 0
|
本帖最后由 bjtulq 于 2011-04-02 17:05 编辑
- /*
- *Send a UDP datagram to a daytime server on some other host,
- *read the reply, and print the time and date on the server.
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
-
- #define BUFFSIZE 150
- #define SERVER_ADDR "202.112.10.60"
- #define SERVER_PORT 123
- int
- main()
- {
- struct sockaddr_in serv;
- char buff[BUFFSIZE];
- int sockfd, n;
- if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
- printf("socket error");
-
- bzero((char *) &serv, sizeof(serv));
- serv.sin_family = AF_INET;
- serv.sin_addr.s_addr = inet_addr(SERVER_ADDR);
- serv.sin_port = htons(SERVER_PORT);
-
- if (sendto(sockfd, buff, BUFFSIZE, 0,
- (struct sockaddr *) &serv, sizeof(serv)) != BUFFSIZE)
- printf("sendto error");
-
- if((n = recvfrom(sockfd, buff, BUFFSIZE, 0,
- (struct sockaddr *) NULL, (socklen_t *) NULL)) < 2)
- printf("recvfrom error");
- buff[n-2] = 0;
- printf("%s\n", buff);
-
- exit(0);
- }
复制代码 |
|