1

I'm writting a UDP server program in Android 4.0 (api 15) when program started, I cann't connect to the UDP server in android

environment:

virtualbox, android x84 4.0, ping to/from virtualbox-android are ok,

UDP server code:

DatagramSocket ds = new DatagramSocket(9101);
<uses-permission android:name="android.permission.INTERNET" />

netstat in android shows:

udp6    0    0    :::9101    :::*    CLOSE

how can I make a normal IPv4 UDP Listening socket?

OItisTang
  • 11
  • 1

2 Answers2

0

Try

DatagramSocket ds = new DatagramSocket(9101, InetAddress.getByName("192.168.1.1"));

and see if that works out. You can also create the socket first and bind it later, like:

DatagramSocket ds = new DatagramSocket(null);
ds.bind(new InetSocketAddress("192.168.1.1", 9101));
ldx
  • 3,984
  • 23
  • 28
0

You can't receive or do network traffic in the main thread.

You have to create a separate runnable thread to do that:

new Thread(new Runnable() {
    public void run() {
    try {
           if (clientsocket == null) {
        clientsocket = new DatagramSocket(null);
            clientsocket.bind(new InetSocketAddress("0.0.0.0", 1337));
        clientsocket.setBroadcast(true);
       }
           byte[] receivedata = new byte[1024];
       while (true) {
        DatagramPacket recv_packet = new DatagramPacket(
        receivedata, receivedata.length);
        clientsocket.receive(recv_packet);
            alertMessage = new String(recv_packet.getData());
        InetAddress ipaddress = recv_packet.getAddress();
        int port = recv_packet.getPort();
        String msg = "RECEIVED UDP MSG FROM " + ipaddress.toString() + ":" + Integer.toString(port) + " :" + alertMessage;  Log.d("UDP", msg);
        myHandler.post(alertMsg);
        }
    } catch (Exception e) {
        Log.e("UDP", "S: Error", e);
    }
      }
}).start();

then in a separate class code the runnable task that could interfere with the main UI.

final Runnable alertMsg = new Runnable() {
    public void run() {
        Toast.makeText(getApplicationContext(), alertMessage, Toast.LENGTH_LONG).show();
    }
};
FranZ
  • 68
  • 3