Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

udp forwarding to emulator

I have a java application on my host that sends UDP packets to a port: e.g. 8888.
And I have an Android application that listens to this port and simply displays the data.

This works fine with a real device (which is connected via WiFi to the same network), but I cannot get this working in the Emulator.

Some info:

  • I am working on Ubuntu 16.10
  • I have deactivated the Ubuntu firewall
  • Start the Android emulator app via IntelliJ
    • the emulator has API level 25
  • I use udp port forwarding as explained in the Android docs:
    telnet localhost 5554 redir add udp:8888:8888

the code in the Android app to connect to the port:

final DatagramSocket udpSocket = new DatagramSocket(8888);

here's the (pseudo) code of the server that sends the broadcast:

String data = "test";
InetAddress broadcastAddress = Inet4Address.getByName("255.255.255.255");
DatagramSocket udpSocket = new DatagramSocket();
udpSocket.setBroadcast(true);
byte[] dataBytes = data.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(dataBytes, dataBytes.length, broadcastAddress, 8888);
udpSocket.send(datagramPacket);

What am I missing?

like image 275
TmTron Avatar asked Feb 19 '26 20:02

TmTron


2 Answers

This does not work because of a bug in Android: Issue#207602: Emulator does not redirect UDP packets

Workaround:

  • in a terminal:
    • get a list of your avds:
      emulator -list-avds
    • start the emulator with one of the avds and add the -engine classic parameter:
      emulator -avd Nexus_6_API_25_GER -engine classic
  • then start your app in Android Studio:
    Run - Run 'app' and connect to the emulator that you have just started
  • in the terminal (maybe another terminal) setup the udp port redirection:
    telnet localhost 5554 redir add udp:8888:8888
  • note: I saw some problems in newer emulators when using the -engine classic (pixel launcher crashes), but my application worked and it received the UDP packets from the host
like image 189
TmTron Avatar answered Feb 22 '26 10:02

TmTron


As TmTron say this problem is because of a bug, but you need also to redirige the UDP packets from your local IP address (192.168.1.X) to yout localhost (127.0.0.1) or the emulated device will not receive the packet. For doing this you can create a simple UDP rediriger or use the program I created to do the same thing https://github.com/danidis91/Port-forward-UDP

like image 24
danidis Avatar answered Feb 22 '26 09:02

danidis