s_addr字段在所有平台上始终以网络(大端)字节顺序存在,因此内部表示是一致的,您不需要进行大小端检查/校正。
没有标准宏类似于CLASS_C_NETMASK、CLASS_B_NETMASK等,使用手动生成的掩码(例如:0xFF000000,0x00FF0000等)更为合适也没有意义。由于子网掩码在一个网络到另一个网络是不固定的,您需要向代码提供实际的网络IP和其子网掩码(提示用户、查询操作系统等)。然后,您可以计算子网的起始IP和结束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的屏蔽,查看结果是否一致(即它们是否在同一子网中):
Or simpler, mask both network IP and target IP with the subnet mask and see if the resulting values are the same (ie, they are the same subnet):
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...
sockets库中是否存在可以检查IP地址是否在IP地址范围内或匹配子网掩码的现有函数?
没有。但手动实现非常简单,只需要几行代码,如上所示。
s_addr
始终采用“网络字节顺序”,即大端(Big-Endian)格式。 - zneak