• 一个简单的时间获取客户端程序


    宏定义:

    /* Following shortens all the typecasts of pointer arguments: */
    #define SA struct sockaddr

    /* Miscellaneous constants */
    #define MAXLINE 4096 /* max text line length */
    #define BUFFSIZE 8192 /* buffer size for reads and writes */

    包裹函数:

    int Socket()
    {
      int n;
      n = socket(AF_INET, SOCK_STREAM, 0);
      if (n < 0)
      {
        printf("socket error:%s ", strerror(errno));
        exit(n);
      }

      return n;
    }

    void Inet_pton(int af, const char *src, void *dst)
    {
      int n;
      n = inet_pton(af, src, dst);
      if (n <= 0)
      {
        printf("inet_pton error:%s ", strerror(errno));
        exit(n);
      }
    }

    int main(int argc, char* argv[])
    {
      int fd;
      int n;
      struct sockaddr_in servaddr;
      char buf[MAXLINE + 1];
      fd = Socket();

      bzero(&servaddr, sizeof(servaddr));
      servaddr.sin_family = AF_INET;
      servaddr.sin_port = htons(2300);


      Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

      if (connect(fd, (SA *)&servaddr, sizeof(servaddr)) < 0)
      {
        printf("connect error:%s ", strerror(errno));
        exit(errno);
      }

      while ( (n = read(fd, buf, MAXLINE)) > 0)
      {
        buf[n] = 0;
        if (EOF == fputs(buf, stdout))
        {
          printf("fputs error:%s ");
          exit(EOF);
        }
      }

      if (n < 0)
      {
        printf("read error:%s ", strerror(errno));
        exit(errno);
      }

      exit(0);
    }

    说明:

    1、使用SA是为了方便书写,"struct sockaddr"长达15个字符。

    2、bzero不是一个ANSI C函数,但是bzero比memset更好记忆。最好使用bzero

    3、inet_pton函数,他是一个支持IPV6的新函数。

  • 相关阅读:
    2、成员对象与封闭类(类与类之间的关系——复合)
    3、常量成员函数
    4、友元
    1、this指针与静态成员
    模拟标准库vetor类写一个简易的变长整数型数组
    运算符重载为友元函数
    左值和右值
    浅拷贝和深拷贝
    赋值运算符
    函数的返回值是如何回到调用处的?
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/4737728.html
Copyright © 2020-2023  润新知