linux 兩次 connect()

就是有時間研究這個。
一個已經 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 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章