我设法从特定请求的网络适配器使用以下代码获取主机信息,但我不知道如何从主机IP地址获取对端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 *)ð->sa_data[2];
unsigned short *high = (unsigned short*)ð->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