转换 IP 以进行反向 ip 查找

标签 c string ip-address reverse

我有一个 IP 地址,例如char *ip = "192.168.1.13" 需要转换成这个"13.1.168.192" 在 C 中是否已经存在适当的可能性,还是我必须通过简单地制作 token 并将它们重新放在一起来自己完成?

最佳答案

您始终可以使用 inet_pton 将其转换为二进制形式,使其易于逆向,然后使用 inet_ntop 转换回文本。


请记住,IPv4 地址只是一个 32 位无符号整数。交换其周围的字节非常容易。

像这样:

const char ip[] = "192.168.0.1";
char reversed_ip[INET_ADDRSTRLEN];

in_addr_t addr;

/* Get the textual address into binary format */
inet_pton(AF_INET, ip, &addr);

/* Reverse the bytes in the binary address */
addr =
    ((addr & 0xff000000) >> 24) |
    ((addr & 0x00ff0000) >>  8) |
    ((addr & 0x0000ff00) <<  8) |
    ((addr & 0x000000ff) << 24);

/* And lastly get a textual representation back again */
inet_ntop(AF_INET, &addr, reversed_ip, sizeof(reversed_ip));

在此代码之后,变量 reversed_ip 包含字符串形式的反向地址。

关于转换 IP 以进行反向 ip 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16373248/

相关文章:

c - TCP套接字编程

php - 查找通过代理连接的客户端的 IP 地址

python - 为什么这个 Python "any"函数不返回 True?

string - 在 PowerBuilder 中使用两个值填充下拉列表框 (DDLB)

ip-address - 我可以使用哪些服务根据用户的 IP 地址查找用户的位置?

java - Java中如何查找IP地址建立的TCP连接数?

c - 分解具有特定结构的原始字节字符串会给出错误的数据

c - C 指针表示法中的这些数组发生了什么?

带有未声明变量的逗号运算符 - 为什么它可以编译?

php - 在 PHP 中用任意数量的空格拆分字符串