c++ - 如何递增表示为字符串的 IP 地址?

标签 c++ string ip-address

我有一个 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/

相关文章:

java - 将JavaFX TextField的内容转换为Integer

javascript - 在 JavaScript 中连接字符串的最有效方法是什么?

java - 将数组的随机字母保存为字符串

c++ - 如何使用 cmake 组织大型构建

c++ - 捕获 lambda 表达式中的非类型模板参数

c++ - 哪些因素使迭代器在 Debug模式下如此缓慢(VC++ 2012)

c++ - 动态改变源IP地址

python - 通过python正则表达式忽略ip地址第一个八位字节中的这两个数字(以127或0开头)

logging - 如何 grep 服务器访问日志以查找唯一 IP 和特定页面?

为 32 位和 64 位处理器强制对齐的 C++ 安全性