3
I am developing an application to turn off the PC’s of a laboratory. I have a reference to class InetAddress
, invoking the method getLocalhost()
. Then I throw it in a array
byte and then I did a for
to display the IP in sequence.
But how is a array
bytes, if the address is as in my case: 10.248.72.58, it displays as follows: 10. -8.72.58, per byte, the range of numbers that "fit" from -128 to 127 (8 bits).
Only if I change to int
, error when calling the function (which returns byte), so the array
has to be byte.
InetAddress localhost = InetAddress.getLocalHost(); // Pega o nome do host do sistema,
//resolvendo pra um objeto InetAddress. Faz cache do endereço por um curto periodo de tempo
byte[] ip = localhost.getAddress();
for (int i = 0; i < 4; i++) {
System.out.println("Ip: " + (byte)ip[i]);
}
Output: Ip: 10. -8.72.58
I’ve tried to cast the value inside the for and it didn’t work.
– Fabricio
Use the
getHostAddress()
doesn’t suit you?– Franchesco
I was going to suggest something but I don’t know if in the Java world it would be seen as gambiarra (despite my points in the tag I never did a program in Java in life). Take the amount in byte, do cast for integer and sum 127.
– Oralista de Sistemas
@Renan is a good solution (if you first check if the number is negative and add 256 instead of 127). Could post as answer.
– Math
@Math I think adding 256 to one byte in java gives the same original number. If we take the two extremes: -127 + 127 gives 0 (the smallest possible value for an IP fragment). 128 + 127 gives 255 (the highest possible value).
– Oralista de Sistemas
@Renan but the idea is just to arrive
no mesmo número original
, isn’t? However after it is already being stored in a variable that supports more bits. Run a C# test (or any language) just to validate the logic.– Math
@Math reread the question and saw that my solution really causes confusion and adds problems instead of solving them. Thanks!
– Oralista de Sistemas