CodeNoob
CodeNoob

Reputation: 365

"Address already in use" DataramSocket in receive datagram

I have a problem (obviously). I am noob in UDP in java sorry.

I am making an application for sending and receive UDP datagrams.The idea to run 2 times the same program and send and receive packets, which I am doing with threads. The problem , receibve this program always gives me the same message.

java.net.BindException: Address already in use

It has to do with the port that I try to open in use, but I do so with any port you try, 80, 8080, 12345. Even watch online command ports were free, but if you tell me who are equally busy.

netstat -a

The code is :

Sender

class envioNodo extends Thread {
byte[] tablaEnca = new byte[10000];
int port = 0;
int puertoVecino = 0;
String IP_envio = "" , IP_emisor ="";
public envioNodo(String tE , String IP , int puerto , String IP_e) {
    port = puerto;
    IP_envio = IP;
    IP_emisor = IP_e;
    System.out.println("Se enviará el vector de distancias a la IP "+ IP_envio +" con puerto "+ port);
}
public void run() {
    System.out.println("Se ejecuta el envio de paquetes del nodo");
    try {
        DatagramSocket dS = new DatagramSocket(); // null //Sin null envia los datos por un puerto cualquiera udp

        dS.setReuseAddress(true);

        DatagramPacket dP = null;
            try {
                dP = new DatagramPacket(tablaEnca , tablaEnca.length, InetAddress.getByName(IP_envio)  , port); 
                dS.send(dP);
                System.out.println("Paquete enviado");

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            }
            try {
                dS.send(dP);
            } catch (IOException e) {
                e.printStackTrace();
            } 
            dS.close();

    } catch (SocketException e) {
        e.printStackTrace();
    }
}

}

Receive

class recepcionNodos extends Thread {
int port = 0;
String vD_rN ;
byte[] buff = new byte[10000];
DatagramPacket dP = null;
DatagramSocket dS = null;
public recepcionNodos(int puerto){
    port = puerto;
    System.out.println("Inicio del hilo de espera de respueta");
    System.out.println("El puerto por el que se escuchara es el "+ port);
}
public void run(){
    do{
        try {
            System.out.println("Comienzo recepcion");
            port++;
            dS = new DatagramSocket(port);
            dP = new DatagramPacket(buff,buff.length);
            System.out.println("Espera en el receive");
            dS.receive(dP);
            vD_rN = new String(dP.getData()).substring(0,dP.getLength());
            System.out.println("String recibido.");
            System.out.print(vD_rN);
            System.out.println("Paquete recibido!");
        } catch (IOException e) {
            System.out.println("Error en recepcion del paquete!");
            e.printStackTrace();
            System.exit(1);
        }

    }while(true);
}

Whit DatagramSocket and DatagramPacket = null.

I Start whit send DatagramSocket = new DatagramSocket(); In this position the constructor get first port can send datagram , ¿But receive i dont know , How do can't receive the packets UDP?

Edit : i have 2 interfaces 10.0.0.1 10.0.0.2 and run one program en one interface whit :

Sudo ip addr add

Solution :

class recepcionNodos extends Thread {
    int port = 0 , aux = 0;
    String vD_rN ;
    byte[] buff = new byte[10000];
    DatagramPacket dP = null;
    DatagramSocket dS = null;
    public recepcionNodos(int puerto){
        port = puerto;
        System.out.println("Inicio del hilo de espera de respueta");
        System.out.println("El puerto por el que se escuchara es el "+ port);
    }
    public void run(){
        do{
            try {
                System.out.println("Comienzo recepcion");
                port++;
                dS = new DatagramSocket(port);

                dP = new DatagramPacket(buff,buff.length);
                System.out.println("Espera en el receive");
                dS.receive(dP);
                vD_rN = new String(dP.getData()).substring(0,dP.getLength());
                System.out.println("String recibido.");
                System.out.print(vD_rN);
                System.out.println("Paquete recibido!");
            } catch (IOException e) {
                System.out.println("Error en recepcion del paquete!");
                e.printStackTrace();
                e.printStackTrace();
                Rip r = new Rip();
                port = Rip.generarPuerto(); // and this function
                System.out.println(port);
                if(aux != 0)
                 System.exit(1);
                aux++;

            }

        }while(true);
    }

This is :

public static int generarPuerto() {
        int aux = 0;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Random r = new Random();
        r.setSeed(r.nextLong());
        aux = r.nextInt(49151 - 1024 - 1) + 1024;
        return aux;
}

My problem is :

2 interfaces :

10.0.0.1
10.0.0.2

And run in a aplication whit 1 IP and other whit other IP , but i think the ports is independents . I use this function and no broblem , but now have the problem i can't receive mensage.

PD : And any whit very much experience or reputation wants to reform the post is free. PD2 : Sorry , very long post and very much edits. PD3 : Very much thx for help , this forum is the best for problems programming.

Upvotes: 1

Views: 4352

Answers (4)

Titus
Titus

Reputation: 22474

You need to close the socket before you open another one. For example:

do{
    try {
        //Create a new socket.
        dS = new DatagramSocket(port);
        dP = new DatagramPacket(buff,buff.length);
        dS.receive(dP);
        vD_rN = new String(dP.getData()).substring(0,dP.getLength());
        System.out.println(vD_rN);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
       //Close the socket and free the port after the message was received.
       if (dS != null) {
           dS.close();
       }
    }
}while(true);

Upvotes: 1

"Address already bind exception", You can make only one socket to run on a particular port. As both sender and receiver are in same program you can use different ports for sender and receiver and try it.

Upvotes: 0

question
question

Reputation: 410

The problem is in your port. Check your port of Server code. If you have two Server running on the same system when same port numbers the second server will never start because it is already in use by the first Server.

Solution: Use two different port numbers in both Server. For example 7070 for first and 7080 for second server program.

Upvotes: 2

Anubian Noob
Anubian Noob

Reputation: 13596

You can only bind one socket to a port at a time.

Since you're running the program twice locally, both sockets are trying to bind to the same port.

There are a couple of possible fixes:

  1. Have two separate programs on different ports.
  2. Have an easy way to change the port between runs.
  3. Automatically change the port if the original port is in use.

I'd suggest the last option. If you catch that error, try binding to a secondary port. When you try to send a packet, send it to both sockets. That'd be a quick and easy solution.

Upvotes: 0

Related Questions