我有一个 char 类型的 IP 地址,比如 char ip = "192.123.34.134"我想增加最后一个值 (134)。有没有人我应该怎么做?我想,我应该把它转换成一个整数,然后再转换回来,但不幸的是我不知道怎么做? :( 我正在使用 C++。
请帮帮我!
谢谢你了
最佳答案
您可以使用 inet_addr
将 IP 地址从字符串转换为整数,然后,在对其进行操作之后,将其转换回带有 inet_ntoa
的字符串.
参见 the documentation对于这些功能,了解有关如何使用它们的更多信息。
这是一个小函数,可以做你想做的事:
// NOTE: only works for IPv4. Check out inet_pton/inet_ntop for IPv6 support.
char* increment_address(const char* address_string)
{
// convert the input IP address to an integer
in_addr_t address = inet_addr(address_string);
// add one to the value (making sure to get the correct byte orders)
address = ntohl(address);
address += 1;
address = htonl(address);
// pack the address into the struct inet_ntoa expects
struct in_addr address_struct;
address_struct.s_addr = address;
// convert back to a string
return inet_ntoa(address_struct);
}
包括<arpa/inet.h>
在 *nix 系统上,或 <winsock2.h>
在 Windows 上。
关于c++ - 如何递增表示为字符串的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1505676/