18

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!

3 Answers 3

54

Something like this:

InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
    System.out.println(b & 0xFF);
}
Sign up to request clarification or add additional context in comments.

3 Comments

oh and btw the masking with 0xFF is for values over 127
in this case, developer have to handle UnknownHostException
From the javadoc: "If a literal IP address is supplied, only the validity of the address format is checked." Doh, of course you still have to catch it :(
4

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.

6 Comments

A byte has a maximum value of 127. How can you put 192 in this array?
If only there were an unsigned byte type in java.
There is a library from google - Guava. Add it and use like this: import com.google.common.primitives.UnsignedBytes
@eternay it is (-64) & 0xFF == 192, -64 == (byte)192
The most efficient way. It needs only 4 bytes.
|
-1

This works well for me (Kotlin):

    open fun reachable(host: String?): Boolean { // 'host' is string, e.g., "177.111.155.11"
    return try {
        val ipAddress = InetAddress.getByName(host)  // get IP address
        ipAddress.isReachable(2000)         // Is it reachable? T or F
    } catch (e: IOException) {
        CoroutineScope(Main).launch {
            myNote("MyWX LAN Reachable Error", e.message!!) // Display error
        }
        false
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.