Tuesday, June 1, 2010

从远程服务器获得日期数据

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
//#include    <netinet/in.h>    /* sockaddr_in{} and other Internet defns */
#include    <arpa/inet.h>    /* inet(3) functions */
#include    <fcntl.h>        /* for nonblocking */
#include    <netdb.h>
#include    <signal.h>
#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <sys/stat.h>    /* for S_xxx file mode constants */
#include    <sys/uio.h>        /* for iovec{} and readv/writev */
#include    <unistd.h>
#include    <sys/wait.h>
#include    <sys/un.h>        /* for Unix domain sockets */


#define MAXLINE 256
 int
 main(int argc, char **argv)
 {
        int     sockfd,n;
        char    recvline[MAXLINE + 1];
        struct sockaddr_in servaddr;
        if (argc != 2)
             printf("usage: a.out <IPaddress>");
        if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
             printf("socket error");
         bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(13); /* daytime server */
         if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr)<=0)
             printf("inet_pton error for %s", argv[1]);
            if (connect(sockfd, /*  (sockaddr *)*/ &servaddr, sizeof(servaddr)) < 0)
             printf("connect error");
        while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
             recvline[n] = 0;                /* null terminate */
             if (fputs(recvline, stdout) == EOF)
                    printf("fputs error");
        }
if (n < 0)
             printf("read error");
        exit(0);
}

编译为get_data后,使用./getdata 206.168.114.96,可以得到该服务器送出的日期数据。

No comments:

Post a Comment