Example:
// using Integer.parseInt
int i = Integer.parseInt("123");
How would you do the same for?
// using Integer.parseInt
int i = Integer.parseInt("123.45.55.34");
Example:
// using Integer.parseInt
int i = Integer.parseInt("123");
How would you do the same for?
// using Integer.parseInt
int i = Integer.parseInt("123.45.55.34");
You can do it for an IP V4 adress as the parts are just the four bytes of the integer version.
Do this to convert an InetAdress to its integer representation :
Note that you shouldn't use 32 bits integers for IP addresses now, as we're entering the era of IPV6 addresses.
EDIT : to parse a string like "123.45.55.34" to something useful in java, you may use
INetAddress.getByName(yourString)
You need to realize that an IPv4 address in the form 123.45.55.34 is actually 4 three digit numbers representing each byte of the address. Parsing the entire string all at once won't work.
Others have mentioned using an
InetAddress
, but if all you have is a string representation of the IP you can't easily instantiate anInetAddress
as far as I know.What you can do is something like the following:
IPAddressUtil#textToNumericFormatV4
performs better thanString#split
to get bytes of ip, besides, it checks if the ip is validYou're likely to want to do this:
Or this:
Of course, as others have suggested, using
InetAddress
might be more appropriate than doing things yourself...Output: