views:

67

answers:

3

Suppose I have the IP stored in a String:

String ip = "192.168.2.1"

and I want to get the byte array with the four ints. How can I do it? Thanks!

A: 

Each number is a byte, so in your case the appropriate byte[] would be { 192, 168, 2, 1 }.

To be more specific, if you have the string, you first have to split it by the "."s and then parse a byte from each resulting string.

Tal Pressman
He wants to convert from a string to a byte array...
Nick Craver
+5  A: 

Something like this:

InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
    System.out.println(b & 0xFF);
}
daedlus
this should also work nicely for "normal" domain names.
Peter Tillemans
oh and btw the masking with 0xFF is for values over 127
daedlus
A: 

Something like

String ip = "127.0.0.1";
String numbers= "\\.";//the dot char                
String[] result = null;
result = ip.split(numbers);

according to this should works.

Fabio F.