Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337309
  • 博文数量: 31
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1134
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-25 09:41
个人简介

目前任职于搜狐~

文章分类

全部博文(31)

文章存档

2014年(12)

2013年(19)

分类: C/C++

2013-10-13 14:54:43

Linux下建立Socket连接:
 

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <sys/socket.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <netinet/in.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <errno.h>

  9. #define SERVER_PORT 8080

  10. void usage(char *name)
  11. {
  12.         printf("usage: %s IP\n", name);
  13. }
  14. int main(int argc, char **argv)
  15. {
  16.         int server_fd, client_fd, length = 0;
  17.         struct sockaddr_in server_addr, client_addr;
  18.         socklen_t socklen = sizeof(server_addr);

  19.         if(argc < 2)
  20.         {
  21.                 usage(argv[0]);
  22.                 exit(1);
  23.         }
  24.         if((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  25.         {
  26.                 printf("create socket error, exit!\n");
  27.                 exit(1);
  28.         }
  29.         srand(time(NULL));
  30.         bzero(&client_addr, sizeof(client_addr));
  31.         client_addr.sin_family = AF_INET;
  32.         client_addr.sin_addr.s_addr = htons(INADDR_ANY);

  33.         bzero(&server_addr, sizeof(server_addr));
  34.         server_addr.sin_family = AF_INET;
  35.         inet_aton(argv[1], &server_addr.sin_addr);
  36.         server_addr.sin_port = htons(SERVER_PORT);

  37.         if(connect(client_fd, (struct sockaddr*)&server_addr, socklen) < 0)
  38.         {
  39.                 printf("can not connect to %s, exit!\n", argv[1]);
  40.                 printf("%s\n", strerror(errno));
  41.                 exit(1);
  42.         }
  43.         printf("Connect OK!\n");
  44.         return 0;


阅读(2137) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~