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
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.
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());
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With