How to convert an IP to byte?

0

I have this code:

byte bEnviar[] = "jose" .getBytes();

byte ip[] = { 200,0,0,1 };

InetAddress address = InetAddress.getByAddress(ip);

The problem is that it gives me an error of

  

Possible loss when converting from int to byte []

And the example I'm seeing to make my socket has it that way

What step should I take to use it in Bytes mode?

    
asked by Jose Luis 10.09.2017 в 21:10
source

1 answer

1

What happens is that you should not transform an integer to byte because as you warn, it would generate loss of precision. You should use each number as a byte. Here I give you an example:

InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();

//Ejemplo de impresión de la IP
for (byte b : bytes) {
    System.out.println(b & 0xFF);
}
    
answered by 10.09.2017 / 21:23
source