The InetAddress class has a getByAddress method that takes as input a byte array containing IPv4 or IPv6 . But in Java, the maximum value of byte is 128 , that is, some addresses cannot be transferred, for example,

 InetAddress host = InetAddress.getByAddress(new byte[]{192, 168, 0, 1}); 

will swear since 192 and 168 not in the range of byte values.

That is, it turns out that not all addresses can be transferred? Or am I misunderstanding something?

  • The method assumes that it is an array of bytes, and not an array of Byte elements. And since the type of byte is signed, then non-included values ​​in the range of values ​​must be set negative. And the maximum value is not 128, but one less. - Akina

1 answer 1

Classes for working with IP perceive the transmitted bytes as a set of bits, and not as signed values ​​of type byte . Therefore, to transfer values ​​that are out of range, it is enough to bring them to the byte :

 InetAddress host = InetAddress.getByAddress(new byte[]{(byte) 192, (byte) 168, (byte) 0, (byte) 1}); 

Values ​​from 128 to 255 will be reduced to negative values ​​from -1 to -128.

Alternatively, you can use a method that accepts a string :

 InetAddress host = InetAddress.getByName("192.168.0.1");