对于一个初学者来说,把多个头文件封装到unp.h不是很方便学习,遂扩展于此。
daytimetcpcli.c文件如下:
#include <netinet/in.h>
#include <stdio.h>
#include <strings.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define MAXLINE 256
int main(int argc, char **argv)
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if (argc != 2) {
fprintf(stderr, "usage: %s <IPaddress>", argv[0]);
exit(1);
}
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
fprintf(stderr, "socket error");
exit(1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
fprintf(stderr, "inet_pton error fon %s", argv[1]);
exit(1);
}
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
fprintf(stderr, "connect error");
exit(1);
}
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = 0;
if (fputs(recvline, stdout) == EOF) {
fprintf(stderr, "fputs error");
exit(1);
}
}
if (n < 0) {
fprintf(stderr, "read error");
exit(1);
}
exit(0);
}
gcc daytimetcpcli.c -o daytimetcpcli
由于本地没有开启daytime服务,所以直接在网上找了一个,ip: 129.6.15.28 (啥?怎么找的?http://tf.nist.gov/tf-cgi/servers.cgi上多试几个)。
./daytimetcpcli 129.6.15.28
如果成功的话,应该是如下返回:
58069 17-11-12 12:25:03 00 0 0 922.8 UTC(NIST) *