Manuel Araoz
Manuel Araoz

Reputation: 16406

how to get a byte[] representation from a IP in String form in Java

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!

Upvotes: 18

Views: 45787

Answers (3)

Dave Enstrom
Dave Enstrom

Reputation: 113

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
    }
}

Upvotes: -1

Inv3r53
Inv3r53

Reputation: 2959

Something like this:

InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
    System.out.println(b & 0xFF);
}

Upvotes: 54

Tal Pressman
Tal Pressman

Reputation: 7317

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.

Upvotes: 4

Related Questions