Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

bytearray

ip

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!

like image 749
Manuel Araoz Avatar asked Jun 06 '10 14:06

Manuel Araoz


People also ask

What is byte [] in Java?

A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.

Can we convert String to byte array in Java?

How to convert String to byte[] in Java? In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .

Can we convert byte to String in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


2 Answers

Something like this:

InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
    System.out.println(b & 0xFF);
}
like image 55
Inv3r53 Avatar answered Oct 14 '22 19:10

Inv3r53


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.

like image 29
Tal Pressman Avatar answered Oct 14 '22 19:10

Tal Pressman