Android UDP can't receive from outside LAN

2019-09-19 11:44发布

问题:

My code can't receive UDP messages from outside my home net. The communication is between Android and Java computer application, with IP inside my LAN (for example 192.168.0.3) the code works, if I put my Java computer application inside my online server (and obviously I changed every IP with external IPs) this doesn't work; Android can send but it can't receive.

Android code :

@Override
protected Integer doInBackground(Void... params) {
    DatagramSocket socket = null;
    byte[] buf = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    try {
        socket = new DatagramSocket(25565);
    } catch (Exception e) {
        Log.i("Ex ", "");
    }
    while (true) {
        try {
            socket.receive(packet);
            String message = new String(packet.getData(), 0,packet.getLength());
            Log.i("message", "" + message);
        } catch (IOException e) {
            Log.i("IO Ex", "");
        }
        catch (Exception e){
        }
    }
}

Java computer application code : http://pastebin.com/2hVGeP6R

回答1:

192.168.0.X is an internal NAT address. Any network can use it, but it can't be reached from anywhere outside. You either need to configure your router to pass it through to your PC and hit the router's external IP, or you need a real network address.



回答2:

Read carefully this example. I suppose you that you are trying to read and write in the same socket while it is open. In case it not working paste some more code in order to help you