建立TCP连接时,什么样的地址给套接字?

时间:2015-04-20 13:16:08

标签: c sockets tcp ip ipv6

我有一个程序,它运行以下步骤:

客户方:

  1. 在特定端口上发送UDP请求(多播)
  2. 检查UDP响应
  3. 从回复中提取地址
  4. 设置套接字到地址和特定端口
  5. 服务器端:

    1. 接收并检查特定端口上的UDP请求(多播)
    2. 发送UDP响应及其内部IP地址。
    3. 设置套接字到地址和特定端口
    4. 我的问题是它无法使用ipv6地址: fe80:0000:0000:0000:0223:18ff:feed:ef59

      .. 但它适用于ipv6映射的ipv4地址0000:0000:0000:0000:0000:ffff:0a40:4caf(对应10.64.76.175

      根据维基百科,10.xxx.xxx.xxx ipv4地址是私有类A地址fe80::/10是链接本地地址。 这是我问题的根源吗?

      我从以太网接口获取这两个地址:

        

      ip addr

       2 : enp0s25: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
      pfifo_fast state UP qlen 1000
      
      link/ether 00:23:18:ed:ef:59 brd ff:ff:ff:ff:ff:ff
      
      inet 10.64.76.175/20 brd 10.64.79.255 scope global enp0s25
         valid_lft forever preferred_lft forever
      
      inet6 fe80::223:18ff:feed:ef59/64 scope link 
         valid_lft forever preferred_lft forever
      

      更准确地说,问题来自于这个提取:socket()函数发回错误。

      int SetupTCPClientSocket(const char *host, const char *service) {
        // Tell the system what kind(s) of address info we want
        struct addrinfo addrCriteria;                   // Criteria for address match
        memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
        addrCriteria.ai_family = AF_UNSPEC;              // v4 and v6 is OK
        addrCriteria.ai_socktype = SOCK_STREAM;         // Only streaming sockets
        addrCriteria.ai_protocol = IPPROTO_TCP;         // Only TCP protocol
      
        // Get address(es)
        struct addrinfo *servAddr; // Holder for returned list of server addrs
        int rtnVal = getaddrinfo(host, service, &addrCriteria, &servAddr);
        if (rtnVal != 0)
          DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));
        int sock = -1;
        struct addrinfo *addr;
        for (addr = servAddr; addr != NULL; addr = addr->ai_next) 
        {  
      
          // Create a reliable, stream socket using TCP
          sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
          if (sock < 0)
          {
            continue;  // Socket creation failed; try next address
          }
      
          // Establish the connection to the echo server
          if (connect(sock, addr->ai_addr, addr->ai_addrlen) == 0)
          {
            break;     // Socket connection succeeded; break and return socket
          }
      
          close(sock); // Socket connection failed; try next address
          sock = -1;
        }
      
        freeaddrinfo(servAddr); // Free addrinfo allocated in getaddrinfo()
        return sock;
      }
      

1 个答案:

答案 0 :(得分:1)

对于链接本地地址(fe80:*),您必须附加要进行连接的接口:fe80:0000:0000:0000:0223:18ff:feed:ef59%enp0s25