宏定义:

/* 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\n", 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\n", 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\n", strerror(errno));
    exit(errno);
  }

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

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

  exit(0);
}

说明:

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

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

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

posted on 2015-08-18 09:15  邶风  阅读(355)  评论(0编辑  收藏  举报