gpt4 book ai didi

c - 获取对端IP地址和端口

转载 作者:行者123 更新时间:2023-11-30 16:42:57 25 4
gpt4 key购买 nike

我设法使用下面的代码从特定请求的网络适配器获取主机信息,但我不知道如何从主机 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);

The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returned addr is determined by the socket's address family (see socket(2) and the respective protocol man pages). When addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com