我设法使用下面的代码从特定请求的网络适配器获取主机信息,但我不知道如何从主机IP地址获取对等IP地址。

struct sockaddr_in *sa = (struct sockaddr_in *)&item->ifr_addr;
    ipAddr = ntohl(*((u_int32_t *)&sa->sin_addr));
    if (pIpAddr != NULL)
    {
        *pIpAddr = ipAddr;
    }

    // Get the MAC address
    if ( ioctl(s, SIOCGIFHWADDR, item) < 0 )
    {
        printf("_GetMacAddress : SIOCGIFHWADDR failed!\n");
        return 0;
    }
    else
    {
        struct sockaddr *eth = (struct sockaddr *) &item->ifr_ifru.ifru_hwaddr;
        unsigned long *low = (unsigned long *)&eth->sa_data[2];
        unsigned short *high = (unsigned short*)&eth->sa_data[0];
        //printf("%s : MAC = 0x%04x, 0x%08x", ntohs(*high), ntohl(*low));

        printf("Interface %8s : IP %3d.%3d.%3d.%3d : MAC = %02x:%02x:%02x:%02x:%02x:%02x\n",
            item->ifr_name,
            ((ipAddr >> 24)&0xff), ((ipAddr >> 16)&0xff), ((ipAddr >> 8)&0xff), (ipAddr&0xff),
            ((ntohs(*high)>> 8)&0x00ff), (ntohs(*high)&0x00ff),
            ((ntohl(*low)>> 24)&0x00ff), ((ntohl(*low)>> 16)&0x00ff), ((ntohl(*low)>> 8)&0x00ff), (ntohl(*low)&0x00ff));

        if ((pMacHigh != NULL) && (pMacLow != NULL))
        {
            *pMacHigh = *high;
            *pMacLow = *low;
        }
    }


输出为:

_GetMaxNetworkInterfaces 3
Interface       lo : IP 127.  0.  0.  1 : MAC = 00:00:00:00:00:00
Interface   enp4s0 : IP 192.168.128. 88 : MAC = f4:8e:38:ea:88:23
Interface   wlp5s0 : IP 192.168. 53. 63 : MAC = b8:81:98:b7:71:90

最佳答案

如果服务器正在侦听传入的连接,则当接受新套接字时,可以从第二个参数accept()中获取对等地址。

accept()的手册页:

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);



  参数addr是指向sockaddr结构的指针。如通信层所知,该结构用对等套接字的地址填充。返回的地址的确切格式addr由套接字的地址族(请参阅socket(2)和相应的协议手册页)确定。当addr为NULL时,不填充任何内容。在这种情况下,不使用addrlen,并且也应为NULL。

关于c - 获取对等IP地址和端口,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45626195/

10-15 10:55
查看更多