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

标签 c sockets

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

相关文章:

Python3套接字客户端发送和接收十六进制字符串

c++ - NaN 到 Bool 转换 : True or False?

c - C 中的 2 D 字符数组,其中每个值都是 C 字符串

actionscript-3 - 套接字错误 - 有时?

java - 如何在Java中连接到受密码保护的系统上运行的服务器?

java - 在某些Android设备上严重UDP数据包丢失

c - OSX/Clang 版本的 __progname 获取可执行文件的绝对路径?

c - 如何将 (latitude,longitude) 转换为 (x,y) 坐标?

c - 将输出从 stdout 重定向到字符串?

java - 在服务器端膨胀序列化对象时发生转换错误