代码之家  ›  专栏  ›  技术社区  ›  Christopher

如何从UDP套接字(C/C++)中获取自己的(本地)IP地址

  •  10
  • Christopher  · 技术社区  · 16 年前
    1. 您有多个网络适配器。
    2. 将UDP套接字绑定到本地端口,而不指定地址。
    3. 在其中一个适配器上接收数据包。

    如何获取接收数据包的适配器的本地IP地址?

    问题是,“接收器适配器的IP地址是什么?”不是我们收到的发件人的地址

    receive_from( ..., &senderAddr, ... );
    

    打电话。

    6 回复  |  直到 8 年前
        1
  •  3
  •   Timbo    16 年前

    IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )
    {
        foreach( adapter in EnumAllNetworkAdapters() )
        {
            adapterSubnet = adapter.subnetmask & adapter.ipaddress;
            senderSubnet = adapter.subnetmask & senderAddr;
            if( adapterSubnet == senderSubnet )
            {
                return adapter.ipaddress;
            }
        }
    }
    
        2
  •  3
  •   Rob Wells    16 年前

        3
  •  3
  •   Community CDub    8 年前
        5
  •  -3
  •   diciu    16 年前
    ssize_t
         recvfrom(int socket, void *restrict buffer, size_t length, int flags,
             struct sockaddr *restrict address, socklen_t *restrict address_len);
    
         ssize_t
         recvmsg(int socket, struct msghdr *message, int flags);
    
    [..]
         If address is not a null pointer and the socket is not connection-oriented, the
         source address of the message is filled in.
    

    int nbytes = recvfrom(sock, buf, MAXBUFSIZE, MSG_WAITALL, (struct sockaddr *)&bindaddr, &addrlen);

        6
  •  -3
  •   Rostyslav Dzinko Ankit    12 年前

    gethostbyname("localhost");