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
I would write a method that accepts a string in that format.
Convert it to 4 integers. increment. (Important Check range)
Then convert back to a string.
If you want somthing more long term and robust a class representing the IP address. Then you maintain the class an manipulate as appropraite and convert to string when needed.
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 withinet_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:
Include
<arpa/inet.h>
on *nix systems, or<winsock2.h>
on Windows.Quick/Dirty!
You can also use the location of the last "." and take from there to the end to convert to an int, bump it up 1, check boundaries and then convert it to a string and append to the base part.
This probably isn't very sane but it was fun to think about.
Since the IP address space is 32-bits you could write a function to convert IP addresses into unsigned 32-bit integers. Then you can add or subtract 1 or as much as you want, and convert back into an IP address. You wouldn't have to worry about range checking.
In pseduo-code for 192.123.34.134 you'd do:
More generally, for a.b.c.d:
Now change
i
as much as you want (i++
,i+=10000
) and convert back:Excuse the syntax - I couldn't write C++ to save myself.
MK