《unix高级环境编程》套接字——基于 socket 的编程

来源:互联网 发布:seo入门资料 编辑:程序博客网 时间:2024/06/05 13:25

基于套接字的连接建立成功之后,就可以进行通信,下面是基于套接字的编程的过程:


在基于 TCP 的通信连接请求过程有三次握手,其过程如下所示:

  • 第一次握手:客户端发送syn包(seq=x)到服务器,并进入SYN_SEND状态,等待服务器确认;
  • 第二次握手:服务器收到syn包,必须确认客户的SYN(ack=x+1),同时自己也发送一个SYN包(seq=y),即SYN+ACK包,此时服务器进入SYN_RECV状态;
  • 第三次握手:客户端收到服务器的SYN+ACK包,向服务器发送确认包ACK(ack=y+1),此包发送完毕,客户端和服务器进入ESTABLISHED状态,完成三次握手。


数据传输过程如下图所示:


关闭通信时,需要四次挥手过程,如下所示:

  • 第一次挥手:主动关闭方发送一个FIN,用来关闭主动方到被动关闭方的数据传送,也就是主动关闭方告诉被动关闭方:我已经不会再给你发数据了(当然,在fin包之前发送出去的数据,如果没有收到对应的ack确认报文,主动关闭方依然会重发这些数据),但此时主动关闭方还可以接受数据。
  • 第二次挥手:被动关闭方收到FIN包后,发送一个ACK给对方,确认序号为收到序号+1(与SYN相同,一个FIN占用一个序号)。
  • 第三次挥手:被动关闭方发送一个FIN,用来关闭被动关闭方到主动关闭方的数据传送,也就是告诉主动关闭方,我的数据也发送完了,不会再给你发数据了。
  • 第四次挥手:主动关闭方收到FIN后,发送一个ACK给被动关闭方,确认序号为收到序号+1,至此,完成四次挥手。


下面是基于套接字的编程:

客户端:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 基于TCP协议面向连接的客户端进程 */  
  2.   
  3. #include "apue.h"  
  4. #include <netdb.h>  
  5. #include <errno.h>  
  6. #include <sys/socket.h>  
  7. #include "connectre.h"  
  8.   
  9. /* 地址的最长大小 */  
  10. #define MAXADDRLEN 256  
  11. /* 缓冲区大小 */  
  12. #define BUFLEN 128  
  13.   
  14. /* 外部函数定义,该函数功能是实现套接字连接 */  
  15. //extern int connect_retry(int sockfd, const struct sockaddr *addr, socklen_t len);  
  16.   
  17. /* 打印客户端所接收的数据信息 */  
  18. void print_uptime(int sockfd);  
  19.   
  20. int main(int argc, char *argv[])  
  21. {  
  22.     struct addrinfo *ailist, *aip;  
  23.     struct addrinfo hint;  
  24.   
  25.     int sockfd, err;  
  26.     if(argc != 2)  
  27.         err_quit("usage: %s hostname", argv[0]);  
  28.     /* 初始化addrinfo结构变量hint */  
  29.     hint.ai_flags = 0;  
  30.     hint.ai_family = 0;  
  31.     hint.ai_socktype = SOCK_STREAM;/* 有序、可靠、双向的面向连接字节流 */  
  32.     hint.ai_protocol = 0;/* 使用默认协议 */  
  33.     hint.ai_addrlen = 0;  
  34.     hint.ai_canonname = NULL;  
  35.     hint.ai_addr = NULL;  
  36.     hint.ai_next = NULL;/* 表示只有一个addrinfo链表结构 */  
  37.   
  38.     /* 将主机名和服务名映射到一个地址 */  
  39.     if((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0)  
  40.         err_quit("getaddrinfo error: %s", gai_strerror(err));  
  41.     /* 对每个结构addrinfo链表进行以下操作,其实这里只有一个addrinfo结构 */  
  42.     for(aip = ailist; aip != NULL; aip = aip->ai_next)  
  43.     {  
  44.         /* 其中这里才是客户端套接字编程 */  
  45.   
  46.         /* 步骤1:创建套接字描述符 */  
  47.         if((sockfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0)  
  48.             err =errno;  
  49.         /* 步骤2:connect请求连接 */  
  50.         if(connect_retry(sockfd, aip->ai_addr, aip->ai_addrlen) < 0)  
  51.             err = errno;/* 请求连接失败 */  
  52.         else /* 请求连接成功,则准备传输数据 */  
  53.         {  
  54.             /* 接收来自服务器进程的消息,并打印输出 */  
  55.             print_uptime(sockfd);  
  56.             exit(0);/* 正常退出 */  
  57.         }  
  58.     }  
  59.     /* 异常退出 */  
  60.     fprintf(stderr, "can't connect to %s: %s\n",argv[1], strerror(err));  
  61.     exit(1);  
  62. }  
  63.   
  64. void print_uptime(int sockfd)  
  65. {  
  66.     int n;  
  67.     char buf[BUFLEN];  
  68.   
  69.     /* 接收数据 */  
  70.     while((n = recv(sockfd, buf, BUFLEN, 0)) > 0)  
  71.         /* 把接收到的数据输出到终端 */  
  72.         write(STDOUT_FILENO, buf, n);  
  73.     if(n < 0)  
  74.         err_sys("recv error");  
  75. }  

服务器端:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 基于TCP的面向连接的服务器进程 */  
  2.   
  3. #include "apue.h"  
  4. #include <netdb.h>  
  5. #include <errno.h>  
  6. #include <syslog.h>  
  7. #include <fcntl.h>  
  8. #include <sys/socket.h>  
  9. #include <sys/wait.h>  
  10. #include "serverin.h"  
  11.   
  12. /* 定义等待请求队列的最大数 */  
  13. #define QLEN 10  
  14.   
  15. #ifndef HOST_NAME_MAX  
  16. #define HOST_NAME_MAX 256  
  17. #endif  
  18.   
  19. /* 外部定义的服务器初始化套接字端点 */  
  20. //extern int initserver(int type, const struct sockaddr *addr, socklen_t len, int qlen);  
  21.   
  22. /* 服务器接收连接请求,并向请求客户端发送数据 */  
  23. void server(int sockfd);  
  24.   
  25. int main(int argc, char *argv[])  
  26. {  
  27.     struct addrinfo *ailist, *aip;  
  28.     struct addrinfo hint;  
  29.   
  30.     int sockfd, err, n;  
  31.     char *host;  
  32.   
  33.     if(argc != 1)  
  34.         err_quit("usage: %s", argv[0]);  
  35. #ifdef _SC_HOST_NAME_MAX  
  36.     n = sysconf(_SC_HOST_NAME_MAX);  
  37.     if(n < 0) /* best guess */  
  38. #endif  
  39.         n = HOST_NAME_MAX;  
  40.     host = (char *)malloc(n);  
  41.     if(NULL == host)  
  42.         err_sys("malloc error");  
  43.     /* 获取客户端的主机名 */  
  44.     if(gethostname(host, n) < 0)  
  45.         err_sys("gethostname error");  
  46.     daemonize("ruptimed");  
  47.     /* 初始化addrinfo结构变量hint */  
  48.     hint.ai_flags = AI_CANONNAME;/* 需要一个规范名 */  
  49.     hint.ai_family = 0;  
  50.     hint.ai_socktype = SOCK_STREAM;/* 有序、可靠、双向的面向连接字节流 */  
  51.     hint.ai_protocol = 0;/* 使用默认协议 */  
  52.     hint.ai_addrlen = 0;  
  53.     hint.ai_canonname = NULL;  
  54.     hint.ai_addr = NULL;  
  55.     hint.ai_next = NULL;/* 表示只有一个addrinfo链表结构 */  
  56.   
  57.     /* 将主机名和服务名映射到一个地址 */  
  58.     if((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0)  
  59.     {  
  60.         syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s", gai_strerror(err));  
  61.         exit(1);  
  62.     }  
  63.     /* 对每个结构addrinfo链表进行以下操作,其实这里只有一个addrinfo结构 */  
  64.     for(aip = ailist; aip != NULL; aip = aip->ai_next)  
  65.     {  
  66.         /* 其中这里才是服务进程套接字编程 */  
  67.   
  68.         if((sockfd = initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen, QLEN)) >= 0)  
  69.         {  
  70.             server(sockfd);  
  71.             exit(0);  
  72.         }  
  73.     }  
  74.     exit(1);  
  75. }  
  76. void server(int sockfd)  
  77. {  
  78.     int clfd, status;  
  79.     pid_t pid;  
  80.   
  81.     while(1)  
  82.     {  
  83.         clfd = accept(sockfd, NULL, NULL);  
  84.         if(clfd < 0)  
  85.         {  
  86.             syslog(LOG_ERR, "ruptimed: accept error: %s", strerror(errno));  
  87.             exit(1);  
  88.         }  
  89.   
  90.         if((pid = fork()) < 0)  
  91.         {  
  92.             syslog(LOG_ERR, "ruptimed: accept error: %s", strerror(errno));  
  93.             exit(1);  
  94.         }  
  95.         else if(pid == 0)  
  96.         {  
  97.             if(dup2(clfd, STDOUT_FILENO) != STDOUT_FILENO || dup2(clfd, STDERR_FILENO) != STDERR_FILENO)  
  98.             {  
  99.                 syslog(LOG_ERR, "ruptimed: accept error: %s", strerror(errno));  
  100.                 exit(1);  
  101.             }  
  102.             close(clfd);  
  103.             execl("/usr/bin/uptime""uptime", (char *)0);/* 执行 uptime指令 */  
  104.             syslog(LOG_ERR, "ruptimed: accept error: %s", strerror(errno));  
  105.         }  
  106.         else  
  107.         {  
  108.             close(clfd);  
  109.             waitpid(pid, &status, 0);  
  110.         }  
  111.     }  
  112. }  

其中客户端和服务器端包含的函数头文件内容如下:

服务器:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 服务器初始化套接字端点 */  
  2. #ifndef SERVERIN_H  
  3. #define SERVERIN_H  
  4. #include "apue.h"  
  5. #include <sys/socket.h>  
  6. #include <errno.h>  
  7. #include <syslog.h>  
  8. #include <fcntl.h>  
  9. #include <sys/resource.h>  
  10.   
  11. /* type 套接字类型, qlen是监听队列的最大个数 */  
  12. int initserver(int type, const struct sockaddr *addr, socklen_t len, int qlen)  
  13. {  
  14.     int fd;  
  15.     int err = 0;  
  16.   
  17.     /* 采用type类型默认的协议 */  
  18.     if((fd = socket(addr->sa_family, type, 0)) < 0)  
  19.         return -1;/* 出错返回-1*/  
  20.   
  21.     int reuse = 1;  
  22.   
  23.     if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0)  
  24.     {  
  25.         err = errno;  
  26.         goto errout;  
  27.     }  
  28.     /* 将地址绑定到一个套接字 */  
  29.     if(bind(fd, addr, len) < 0)  
  30.     {  
  31.         err =errno;  
  32.         goto errout;/* 跳转到出错输出语句 */  
  33.     }  
  34.     /* 若套接字类型type是面向连接(SOCK_STREAM, SOCK_SEQPACKET)的,则执行以下语句 */  
  35.     if(type == SOCK_STREAM || type == SOCK_SEQPACKET)  
  36.     {  
  37.         /* 监听套接字连接队列 */  
  38.         if(listen(fd, qlen) < 0)  
  39.         {  
  40.             err = errno;  
  41.             goto errout;  
  42.         }  
  43.     }  
  44.     return (fd);  
  45.   
  46. errout:  
  47.     close(fd);  
  48.     errno = err;  
  49.     return -1;  
  50. }  
  51.   
  52. /* 初始化守护进程 */  
  53.   
  54. void daemonize(const char *cmd)  
  55. {  
  56.     int i, fd0, fd1, fd2;  
  57.     pid_t pid;  
  58.     struct rlimit rl;  
  59.     struct sigaction sa;  
  60.     umask(0);  
  61.   
  62.     if(getrlimit(RLIMIT_NOFILE, &rl) < 0)  
  63.         err_quit("%s: can't get file limit", cmd);  
  64.   
  65.     if((pid =fork()) < 0)  
  66.         err_quit("%s: can't fork", cmd);  
  67.     else if(pid != 0)  
  68.         exit(0);  
  69.     setsid();  
  70.   
  71.     sa.sa_handler = SIG_IGN;  
  72.     sigemptyset(&sa.sa_mask);  
  73.     sa.sa_flags = 0;  
  74.     if(sigaction(SIGHUP, &sa, NULL) < 0)  
  75.         err_quit("%s: can't ignore SIGHUP");  
  76.     if((pid =fork()) < 0)  
  77.         err_quit("%s: can't fork", cmd);  
  78.     else if(pid != 0)  
  79.         exit(0);  
  80.     if(chdir("/") < 0)  
  81.         err_quit("%s: can't change directory to /");  
  82.   
  83.     if(rl.rlim_max == RLIM_INFINITY)  
  84.         rl.rlim_max = 1024;  
  85.     for(i = 0; i < (int)rl.rlim_max; i++)  
  86.         close(i);  
  87.   
  88.     fd0 = open("/dev/null", O_RDWR);  
  89.     fd1 = dup(0);  
  90.     fd2 = dup(0);  
  91.   
  92.     openlog(cmd, LOG_CONS, LOG_DAEMON);  
  93.     if(fd0 != 0 || fd1 != 1 || fd2 != 2)  
  94.     {  
  95.         syslog(LOG_ERR, "unexpectrd file descriptors %d %d %d", fd0, fd1, fd2);  
  96.         exit(1);  
  97.     }  
  98.   
  99. }  
  100. #endif  

客户端:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 建立连接 */  
  2.   
  3. /* 该函数的功能和connect相同,当connect连接出错时,这里支持重试连接 */  
  4.   
  5. #ifndef CONNECTRE_H  
  6. #define CONNECTRE_H  
  7. #include "apue.h"  
  8. #include <sys/socket.h>  
  9.   
  10. #define MAXSLEEP 128  
  11.   
  12. int connect_retry(int sockfd, const struct sockaddr *addr, socklen_t len)  
  13. {  
  14.     int nsec;  
  15.     /* Try to connect with exponential backoff */  
  16.   
  17.     for(nsec = 1; nsec <= MAXSLEEP; nsec <<= 1)  
  18.     {  
  19.         if(connect(sockfd, addr, len) == 0)  
  20.             return 0;  
  21.         /* Delay before trying again */  
  22.         if(nsec <= MAXSLEEP/2)  
  23.             sleep(nsec);  
  24.     }  
  25.     return -1;  
  26. }  
  27. #endif  

输出结果:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 
  2. *在输出结果之前一些准备工作,在文件 /etc/servers 添加 ruptime  4000/tcp 
  3. */  
  4. ./server   
  5. ./client Ubu1204  
  6.  19:49:57 up 3 days, 11:10,  4 users,  load average: 0.62, 1.74, 1.46  
0 0
原创粉丝点击