Doubt about showing local network IP

Asked

Viewed 225 times

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.

  • Use the getHostAddress() doesn’t suit you?

  • 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.

  • @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 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).

  • @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 reread the question and saw that my solution really causes confusion and adds problems instead of solving them. Thanks!

Show 2 more comments

3 answers

5

You can turn the signposted byte to non-signposted so:

ip[i] & 0xFFL;

Example:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IP {
    public static void main(String[] args) throws UnknownHostException {
        InetAddress localhost = InetAddress.getLocalHost(); 
        byte[] ip = localhost.getAddress();
        int[] ip2 = new int[ip.length];
        System.out.println("Imprimindo em byte:");
        for (int i = 0; i < 4; i++) {
            System.out.printf("Ip: %d ", ip[i] & 0xFFL); //imprime não-sinalizado
            ip2[i] = (int) (ip[i] & 0xFFL); //armazenei já como não-sinalizado em um int[]
        }
        System.out.println("\nImprimindo em int:");
        for (int i = 0; i < 4; i++) {
            System.out.printf("Ip: %d ", ip2[i]); //imprime o int não-sinalizado
        }
    }
}

Upshot:

Printing in byte:
Ip: 192 Ip: 168 Ip: 239 Ip: 1
Printing in int:
Ip: 192 Ip: 168 Ip: 239 Ip: 1

4

If it’s just to show the IP you can just use the method getHostAddress().

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

System.out.println("Ip: " + localhost.getHostAddress());

-1

import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;

/**
 * Contém métodos úteis para o sistema
 *
 * @author [email protected] Brasília, 24/08/2017
 */
public class Utils {

    /**
     * Dado um String IP devolve um InetAddress.
     */
    public static InetAddress getInetAddress(String ip) {
        System.out.println("ip = " + ip);

        String[] pedaçoIP = ip.split("[.]");
        if (pedaçoIP.length != 4){
           mostraErro("Utils:getInetAddress():ip mau formado =\"" + ip + "\"" );
        }
        byte[] array = new byte[4];
        for (int i = 0; i < 4; i++) {
            int x = Integer.decode(pedaçoIP[i]);
            array[i] = (byte) x;
            /*
            Acima funciona muito bem, mas se tentar assim, é incompatível!
            array[i] = (byte) Integer.decode(pedaçoIP[i]);
            Mas assim também funciona
            array[i] = (byte) ((int)Integer.decode(pedaçoIP[i]));
            */

        }
        InetAddress address = null;
        try {
            address = InetAddress.getByAddress(array);

        } catch (UnknownHostException ex) {
            mostraErro("Utils:getInetAddress():ip=" + ip + "\nex.getMessage="
                    + ex.getMessage());
        }
        return address;
    }

    /**
     * Mostra uma janela com mensagem de erro.
     */
    public static void mostraErro(String mensagem) {
        System.out.println("ERRO: " + mensagem);
        String[] opções = {"OK, Continuar", "Fechar o Programa"};
        int retorno = JOptionPane.showOptionDialog(null, mensagem,
                "OCORREU UM ERRO", 0, JOptionPane.ERROR_MESSAGE, null, opções, 1);

        if (retorno == 1) {
            System.exit(-1);
        }
    }

    /**
     * Testa os métodos fora do seu contexto.
     */
    public static void main(String[] args) {
        InetAddress address = null;
        address = getInetAddress("127.0.0.1");
        System.out.println("HostAddress = \""+address.getHostAddress()+"\"");
        System.out.println("HostName = \""+address.getCanonicalHostName()+"\"");
        address = getInetAddress("192.168.1.1");
        System.out.println("HostAddress = \""+address.getHostAddress()+"\"");
        System.out.println("HostName = \""+address.getCanonicalHostName()+"\"");
        //mostraErro("Uma mensagem de erro");
    }
}
  • All help is welcome, and it is very good the initiative of a new user already contributing code. Just note that it is important to explain in the answer how such a code is used, and how it solves the problem of what has been asked, so that the community can consciously vote on its answer, and the author of the question actually benefits from the new knowledge. Here are some tips for better use of the site: [Answer], [Tour] and [Help]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.