How do I increment an IP address represented as a string?
c++, ip-address, string
Solution
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.
Problem
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