如何增加表示为字符串的IP地址?

kam*_*mpi 6 c++ string ip-address

我有一个char类型的IP地址像char ip ="192.123.34.134"我想增加最后一个值(134).有人应该怎么做?我想,我应该将它转换为整数,然后再回来,但不幸的是我不知道怎么做?:(我正在使用C++.

请帮我!

谢谢,kampi

Nei*_*ams 24

您可以将IP地址从字符串转换为整数inet_addr,然后在操作之后将其转换回字符串inet_ntoa.

有关如何使用它们的更多信息,请参阅这些函数的文档.

这是一个小功能,可以做你想要的:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

包含<arpa/inet.h>在*nix系统或<winsock2.h>Windows上.