Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DatagramSocket error message: EADDRINUSE (Address already in use)

Tags:

I am trying to write a simple android chat app. I have created a service class which handles all the networking communication. The DatagramSocket binding is in a separate thread. Once in while I am getting this error and the app crashes:

java.net.BindException: bind failed: EADDRINUSE (Address already in use)
at libcore.io.IoBridge.bind(IoBridge.java:89)
at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:68)
at java.net.DatagramSocket.createSocket(DatagramSocket.java:133)
at java.net.DatagramSocket.<init>(DatagramSocket.java:78)

and this is the code which prodruces it. The error occur on the line with new DatagramSocket How can I avoid this error? Thank you.

private class ComThread extends Thread {

        private static final int BCAST_PORT = 8779;
        DatagramSocket mSocket;
        InetAddress myBcastIP, myLocalIP;

        public ComThread() {

            try {
                myBcastIP = getBroadcastAddress();
                if (D)
                    Log.d(TAG, "my bcast ip : " + myBcastIP);

                myLocalIP = getLocalAddress();
                if (D)
                    Log.d(TAG, "my local ip : " + myLocalIP);

                if (mSocket == null) {
                    mSocket = new DatagramSocket(BCAST_PORT);
                    mSocket.setReuseAddress(true);
                    mSocket.setBroadcast(true);
                }           

            } catch (IOException e) {
                Log.e(TAG, "Could not make socket", e);
            }
        }
like image 845
Sean Kilb Avatar asked Nov 26 '12 15:11

Sean Kilb


2 Answers

Since Sean asked for the code, I have translated Nikola's answer to the following code, which is similar to what I am using in my app, in case it is useful:

if (mSocket == null) {
    mSocket = new DatagramSocket(null);
    mSocket.setReuseAddress(true);
    mSocket.setBroadcast(true);
    mSocket.bind(new InetSocketAddress(BCAST_PORT));
}
like image 70
Hong Avatar answered Sep 18 '22 17:09

Hong


You need to set SO_REUSEADDR before binding. Don't specify port in the constructor - create unbound socket instead with DatagramSocket(null), then set options, then bind() explicitly.

like image 18
Nikolai Fetissov Avatar answered Sep 20 '22 17:09

Nikolai Fetissov