• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

new DatagramSocket(int/*port number*/) - "Address already in use"

The line of code that is throwing this exception is in bold text.

The scenario is as follows.

I am looping through stations 1 to m_nMaxStation (24) in function searchForStations().

Each time I am broadcasting (10.0.0.255) the same string for each station.

The broadcast string contains "request`<station number 1-24>`<IP address mobile device".

Example "request`10`10.0.0.23`" (` character is just a delimiter used by the receiver to separate the bits of the string)

After sending my request string 'waitResponse(final int nStation)' is called.

This simply waits for a response from the station number specified in the request string.

If a response is not received within the timeout then that station number is deemed to be inactive.

But this is where the exception is thrown.

The first call to waitResponse(final int nStation) results in no exception being thrown.

But all subsequent calls throw the exception "Address already in use"

How do I fix it?

I have no idea despite searching google for a couple of hours.

Code:
package com.example.greg.irrigationcontroller;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


/**
* Created by Greg on 5/10/2017.
*/

public class CSearchAutoSolActivity extends AppCompatActivity implements View.OnClickListener
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_auto_sol);

        m_app = ((CIrrigationApplication) getApplicationContext());
        m_textviewResults = (TextView)findViewById(R.id.id_textview_results);
        m_textviewTrying = (TextView)findViewById(R.id.id_textview_trying);
        m_progress = (ProgressBar)findViewById(R.id.id_progressbar_search);
        m_buttonStart = (Button)findViewById(R.id.id_button_start);
        m_buttonStart.setOnClickListener(CSearchAutoSolActivity.this);
        m_strUDPDelim = new String("`");
        m_nUDPPort = 10002;
    }

    @Override
    public void onClick(View view)
    {
        Intent intent = null;

        switch (view.getId())
        {
            case R.id.id_button_start:
                m_buttonStart.setEnabled(false);
                m_searchtask = new CSearchTask();
                m_searchtask.execute();
                break;
            case R.id.id_button_back:
                intent = new Intent(getApplicationContext(), CMainActivity.class);
                break;
        }
        if (intent != null)
        {
            finish();
            startActivity(intent);
        }
    }

    protected CIrrigationApplication m_app;
    TextView m_textviewResults, m_textviewTrying;
    Button m_buttonStart;
    ProgressBar m_progress;
    String m_strUDPDelim;
    int m_nUDPPort;
    CSearchTask m_searchtask;


    protected class CSearchTask extends AsyncTask<Void/**param type*/, Void/**progress type*/, String/**result type*/>
    {
        public CSearchTask()
        {
            m_strResults = new String();
            m_strTrying = new String();
            m_nProgress = 0;
        }

        @Override
        protected String doInBackground(Void...Void)
        {
            String strResult = new String("");

            searchForStations();

            return strResult;
        }

        @Override
        protected void onProgressUpdate(Void...param)
        {
            m_textviewResults.setText(m_strResults);
            m_textviewTrying.setText(m_strTrying);
            m_progress.setProgress(m_nProgress);
        }

        @Override
        protected void onPostExecute(String strResult)
        {
            m_buttonStart.setEnabled(true);
            m_textviewTrying.setText("Finished");
        }

        @Override
        protected void onPreExecute()
        {
            if (m_app != null)
            {
                m_wifiManag = (WifiManager) m_app.getSystemService(Context.WIFI_SERVICE);
                if ((m_wifiManag != null) && !m_wifiManag.isWifiEnabled())
                    m_wifiManag.setWifiEnabled(true);
            }
        }

        protected boolean waitResponse(final int nStation)
        {
            boolean bResult = false;
            String strMsg = new String("");
            byte[] buffMsg = new byte[32];
            DatagramPacket datagramPacket = new DatagramPacket(buffMsg, buffMsg.length);
            DatagramSocket datagramSocket;

            try
            {
                datagramSocket = new DatagramSocket(m_nUDPPort);
            }
            catch (IOException ioe)
            {
                m_strResults = "new DatagramSocket() - " + ioe.getMessage();
                return bResult;
            }
            try
            {
                datagramSocket.setSoTimeout(2000);
                datagramSocket.receive(datagramPacket);
                datagramSocket.close();
            }
            catch (IOException ioe)
            {
                m_strResults = "DatagramSocket.receive(...) - " + ioe.getMessage();
                return bResult;
            }
            strMsg = new String(buffMsg, 0, datagramPacket.getLength());
            if (bResult = (strMsg.length() > 0) && strMsg.contains("notify"))
            {
                m_app.setStationActive(nStation, true);
                m_app.setStationIPAddress(nStation, datagramSocket.getInetAddress().getHostAddress());
            }
            return bResult;
        }
        protected void searchForStations()
        {
            if ((m_app != null) && (m_wifiManag != null) && m_wifiManag.isWifiEnabled() && (m_textviewResults != null) && (m_textviewTrying != null))
            {
                InetAddress ipLocal;
                try
                {
                    ipLocal = InetAddress.getLocalHost();
                }
                catch (IOException ioe)
                {
                    m_strResults = "InetAddress.getLocalHost() - " + ioe.getMessage();
                    publishProgress();
                    return;
                }
                DatagramSocket datagramSocket;
                CIPAddress ipIPAddr = new CIPAddress(ipLocal.getHostAddress());
                try
                {
                    datagramSocket = new DatagramSocket();
                }
                catch (IOException ioe)
                {
                    m_strResults = "new DatagramSocket() - " + ioe.getMessage();
                    publishProgress();
                    return;
                }
                String strRequest = new String("request") + m_strUDPDelim, strMsg = new String();
                int nProgressInc = 100 / m_app.m_nMaxStations + 1;
                byte[] buffMsg;
                DatagramPacket datagramPacket;
                boolean bRespRec = false;
                InetAddress ia;
                try
                {
                    ia = InetAddress.getByName(ipIPAddr.toBroadcast());
                }
                catch(IOException ioe)
                {
                    m_strResults = "InetAddress.getByName(...) - " + ioe.getMessage();
                    publishProgress();
                    return;
                }
                for (int nStation = 1; nStation <= m_app.m_nMaxStations; nStation++)
                {
                    m_strTrying = new String("Trying station ") + String.valueOf(nStation) + new String("...");
                    publishProgress();
                    strMsg = strRequest + String.valueOf(nStation) + m_strUDPDelim + ipIPAddr.toString() + m_strUDPDelim;
                    buffMsg = strMsg.getBytes();

                    datagramPacket = new DatagramPacket(buffMsg, strMsg.length(), ia, m_nUDPPort);
                    try
                    {
                        datagramSocket.send(datagramPacket);
                    }
                    catch (IOException ioe)
                    {
                        m_strResults = "DatagramSocket.send(...) - " + ioe.getMessage();
                        publishProgress();
                        return;
                    }
                    bRespRec = waitResponse(nStation);
                    m_strResults += "Station " + String.valueOf(nStation) + ": ";
                    if (bRespRec)
                        m_strResults += "response received from " + m_app.getStationIPAddress(nStation) + "\n\n";
                    else
                        m_strResults += "no response\n\n";
                    m_nProgress += nProgressInc;
                }
            }
        }

        WifiManager m_wifiManag;
        String m_strResults, m_strTrying;
        int m_nProgress;
    }
}
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones