Search code examples
javaudp

Java UDP Client Server Receiving Package wrong result


i am writing a program that receive an IP address from Client then send this IP address to Server, Server will receive the address and convert the address to binary and send back to client to show in the console. I already have the first half but when server send back the Ip address in binary to client I got the wrong result. For example i put put 2.3.4.5 the result is like this

IP 2.3.4.5 en binario: java.net.DatagramPacket@12d4bf7e

How can I fix this error. Thank you.

Class Client

public class SocketUDPClientIP {

public static void main(String[] args) throws IOException {

    Scanner scanner = new Scanner(System.in);
    DatagramSocket clienteSocket = new DatagramSocket();
    InetAddress ipServidor = InetAddress.getLocalHost();
    int puerto = 6666;
    System.out.println("PROGRAMA CLIENTE INICIADO....");

    while (scanner.hasNext()) {
        System.out.println("Introduzca una IP en formato decimal:");
        String ipAd = scanner.nextLine();
        System.out.println("Socket Cliente envía IP " + ipAd);

        byte[] enviados = new byte[1024];
        enviados = ipAd.getBytes();
        // Enviar
        DatagramPacket envio = new DatagramPacket(enviados, enviados.length, ipServidor, puerto);
        clienteSocket.send(envio);
      
        byte[] recibidos = new byte[1024];
        DatagramPacket recibo = new DatagramPacket(recibidos, recibidos.length);
        clienteSocket.receive(recibo);
        System.out.println("Socket Cliente esperando Datagrama del Socket Servidor ..........");
        System.out.println("IP " + ipAd + " en binario: " + recibo);
       
        if (ipAd.equals("0.0.0.0")) {
            break;
        }

    }
}

}

Class Server

public class SocketUDPServerIP {
public static void main(String[] args) throws IOException {

    DatagramSocket socket = new DatagramSocket(6666);
    System.out.println("Servido esperando al cliente.....");

    do {
        DatagramPacket recibo;
        byte[] buffer = new byte[1024];
        recibo = new DatagramPacket(buffer, buffer.length);
        socket.receive(recibo);
        String ipAd = new String(recibo.getData()).trim();
        System.out.println("Recibiendo del CLIENTE: \n\t" + ipAd);

        String[] ipAdS = ipAd.split("\\.");
        int ipAd1 = Integer.parseInt(ipAdS[0]);
        int ipAd2 = Integer.parseInt(ipAdS[1]);
        int ipAd3 = Integer.parseInt(ipAdS[2]);
        int ipAd4 = Integer.parseInt(ipAdS[3]);

        String ipAdBinary = "";
        if (ipAd1 < 256 && ipAd2 < 256 && ipAd3 < 256 && ipAd4 < 256) {
            String ipad1S = Integer.toBinaryString(ipAd1);
            String ipad2S = Integer.toBinaryString(ipAd2);
            String ipad3S = Integer.toBinaryString(ipAd3);
            String ipad4S = Integer.toBinaryString(ipAd4);

            ipAdBinary = ipad1S + "." + ipad2S + "." + ipad3S + "." + ipad4S;
            System.out.println(ipAdBinary);
        } else {
            ipAdBinary = "El IP " + ipAd + " es un IP no valida, introduzca otra IP";
            System.out.println(ipAdBinary);
        }
        InetAddress IPOrigen = recibo.getAddress();
        int puerto = recibo.getPort();
        DatagramPacket envio = new DatagramPacket(ipAdBinary.getBytes(),ipAdBinary.length(),IPOrigen,puerto);
        socket.send(envio);

    } while (true);



}

}


Solution

  • Such output is received because you are attempting to print an instance of a class (DatagramPacket) that does not override the toString() method (which is defined in the superclass java.lang.Object). Instead, you could use the byte array (recibidos), a reference to which was provided to the DatagramPacket constructor (so we consider after executing the receive() method it contains some useful data), instantiate a new String instance representing this byte array in a human-readable format and print it to the console:

    byte[] recibidos = new byte[1024];
    DatagramPacket recibo = new DatagramPacket(recibidos, recibidos.length);
    clienteSocket.receive(recibo);
    System.out.println("Socket Cliente esperando Datagrama del Socket Servidor ..........");
    System.out.println("IP " + ipAd + " en binario: " + (new String(recibidos))); // not using the "recibo" variable anymore