Standard/safe 检查 IP 地址是否在 range/subnet 中的方法

Standard/safe way to check if IP address is in range/subnet

我有一小段代码将一个 32 位无符号整数(即:uint32_t)转换为一组四个 8 位字段,将其视为 IP 地址,然后报告给如果客户端位于预定的 IP 地址范围内。

already found a few different examples of code in C that shows me how to get the IP address of a client from the struct sockaddr_in that contains it, along with a C# answer。但是,我想进一步分解地址,将其保留在纯 C 中,并想快速了解一些事情:

  1. 系统之间的内部表示是否一致,或者我是否需要在 s_addr 字段上执行 Endian-ness checks/correction?
  2. 是否有 CLASS_C_NETMASKCLASS_B_NETMASK 等标准宏,比使用手动生成的掩码更合适(即:0xFF0000000x00FF0000, 等等).
  3. 套接字库中是否有任何现有函数可以检查 IP 地址是否在 IP 地址范围内或是否与子网掩码匹配?

谢谢。

Is the internal representation consistent from system to system, or do I ever need to do Endian-ness checks/correction on the s_addr field?

s_addr 在所有平台上始终采用网络(大端)字节顺序。

Are there standard macros along the lines of CLASS_C_NETMASK, CLASS_B_NETMASK, etc, that would be more appropriate than using manually generated masks (ie: 0xFF000000, 0x00FF0000, etc).

不,使用此类宏也没有意义,因为子网掩码在一个网络和另一个网络之间不是固定的。您需要为代码提供实际的网络 IP 及其子网掩码(提示用户、查询 OS 等)。然后您可以计算子网的起始和结束 IP 以与您的目标 IP 进行比较:

uint32_t ip = ...; // value to check
uint32_t netip = ...; // network ip to compare with
uint32_t netmask = ...; // network ip subnet mask
uint32_t netstart = (netip & netmask); // first ip in subnet
uint32_t netend = (netstart | ~netmask); // last ip in subnet
if ((ip >= netstart) && (ip <= netend))
    // is in subnet range...
else
    // not in subnet range...

或者更简单,用子网掩码屏蔽网络 IP 和目标 IP,并查看结果值是否相同(即它们是相同的子网):

uint32_t ip = ...; // value to check
uint32_t netip = ...; // network ip to compare with
uint32_t netmask = ...; // network ip subnet mask
if ((netip & netmask) == (ip & netmask))
    // is on same subnet...
else
    // not on same subnet...

Are there any existing functions in the sockets library that will do checks if an IP address is in a range of IP addresses or matches a subnet mask?

没有。但是手动实现很简单,只需要几行代码,如上所示。