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.

Share:
39,916

Related videos on Youtube

Manuel Araoz
Author by

Manuel Araoz

I'm just trying to learn a bit of programming.

Updated on July 09, 2022

Comments

  • Manuel Araoz
    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
    Inv3r53 almost 14 years
    oh and btw the masking with 0xFF is for values over 127
  • eternay
    eternay almost 11 years
    A byte has a maximum value of 127. How can you put 192 in this array?
  • Michael Campbell
    Michael Campbell almost 8 years
    If only there were an unsigned byte type in java.
  • RB_
    RB_ almost 6 years
    There is a library from google - Guava. Add it and use like this: import com.google.common.primitives.UnsignedBytes
  • c.sankhala
    c.sankhala about 5 years
    in this case, developer have to handle UnknownHostException
  • Sam Ginrich
    Sam Ginrich over 2 years
    @eternay it is (-64) & 0xFF == 192, -64 == (byte)192
  • Denis
    Denis over 2 years
    The most efficient way. It needs only 4 bytes.
  • The Corn Inspector
    The Corn Inspector almost 2 years
    I love this comment section, the most basic conversion and someone recommended using a library