Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increment an IP address represented as a string?

I have an IP address in char type Like char ip = "192.123.34.134" I want increment the last value (134). Does anyone how should i do it? I think, i should convert it to an integer, and then back, but unfortunately i don't know how? :( I'm using C++.

Please help me!

Thanks, kampi

like image 435
kampi Avatar asked Oct 01 '09 18:10

kampi


3 Answers

You can convert the IP address from a string to an integer using inet_addr, then, after manipulating it, convert it back to a string with inet_ntoa.

See the documentation for these functions for more info on how to use them.

Here's a small function that will do what you want:

// 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);
}

Include <arpa/inet.h> on *nix systems, or <winsock2.h> on Windows.

like image 71
Neil Williams Avatar answered Nov 12 '22 16:11

Neil Williams


Quick/Dirty!

void increment(std::string& ip)
{
    std::string::size_type dot = ip.find_last_of('.');
    std::stringstream stream(ip.substr(dot+1));
    int part = 0;

    stream >> part;

    part++;

    stream.str(""); stream.clear();

    stream << part;

    ip.replace(dot+1, std::string::npos, stream.str());
}
like image 4
Khaled Alshaya Avatar answered Nov 12 '22 17:11

Khaled Alshaya


int a,b,c,d;
sscanf(str, "%d.%d.%d.%d", &a,&b,&c,&d);
sprintf(str, "%d.%d.%d.%d\0", a,b,c,d+1);
like image 3
ragnarius Avatar answered Nov 12 '22 17:11

ragnarius