how to get a byte[] representation from a IP in String form in Java
39,916
Solution 1
Something like this:
InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
System.out.println(b & 0xFF);
}
Solution 2
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.
Related videos on Youtube
Comments
-
Manuel Araoz almost 2 years
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!
-
Inv3r53 almost 14 yearsoh and btw the masking with 0xFF is for values over 127
-
eternay almost 11 yearsA byte has a maximum value of 127. How can you put 192 in this array?
-
Michael Campbell almost 8 yearsIf only there were an unsigned byte type in java.
-
RB_ almost 6 yearsThere is a library from google - Guava. Add it and use like this: import com.google.common.primitives.UnsignedBytes
-
c.sankhala about 5 yearsin this case, developer have to handle UnknownHostException
-
Sam Ginrich over 2 years@eternay it is (-64) & 0xFF == 192, -64 == (byte)192
-
Denis over 2 yearsThe most efficient way. It needs only 4 bytes.
-
The Corn Inspector almost 2 yearsI love this comment section, the most basic conversion and someone recommended using a library