linux 两次 connect()

来源:互联网 发布:python 方括号 编辑:程序博客网 时间:2024/06/05 21:50

就是有时间研究这个。
一个已经 connect() 成功的 fd 再次 connect 会怎么样呢?撸代码试一下就好了。

#include <sys/types.h>#include <sys/socket.h>#include <errno.h>#include <stdio.h>#include <netinet/in.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>int main(){    const char *addr = "127.0.0.1";    unsigned short port = 6379;    struct sockaddr_in sa;    int s = -1;    if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)    {        return -1;    }    sa.sin_family = AF_INET;    sa.sin_port = htons(port);    if (inet_aton(addr, &sa.sin_addr) == 0)    {        return -1;     }    //第一次链接    if (connect(s, (struct sockaddr*)&sa, sizeof(sa)) == -1)    {        perror("error:");    }else    {        printf("ok\n");    }    //在一次链接    if (connect(s, (struct sockaddr*)&sa, sizeof(sa)) == -1)    {        printf("errno=%d\n", errno );        perror("error:");    }else    {        printf("ok\n");    }    close( s );    return 0;}

运行结果:
yuhaiyang-Aspire-4750:~/qt/build-doubleConnect-Desktop-Debug$ ./doubleConnect
ok
errno=106
error:: Transport endpoint is already connected

查头文件 errno = 106

#define EISCONN  106 /* Transport endpoint is already connected */
0 0