Q:

How to receive data using UDP in Android?

I use the following code to receive the data from a particular port. It's not working in Android. But sending data to particular port is working fine.
public class UDPDemo extends Activity {
  private TextView tv;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv = (TextView)findViewById(R.id.recv_message);
    try {
      DatagramSocket clientsocket=new DatagramSocket(9876);
      byte[] receivedata = new byte[1024];
      while(true)
      {
        DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
        Log.d("UDP", "S: Receiving...");
        clientsocket.receive(recv_packet);
        String rec_str = new String(recv_packet.getData());
        tv.setText(rec_str);
        Log.d(" Received String ",rec_str);
        InetAddress ipaddress = recv_packet.getAddress();
        int port = recv_packet.getPort();
        Log.d("IPAddress : ",ipaddress.toString());
        Log.d(" Port : ",Integer.toString(port));
      }
    } catch (Exception e) {
      Log.e("UDP", "S: Error", e);
    }
  }
}

A:

If you are using the emulator you may need setup redirects, remember the emulator is behind a virtual router.
In other words, type these commands in;
telnet localhost 5554
redir add udp:9876:9876

and try again.

