简体   繁体   中英

Android UDP Packets are sent to the wrong address

I am making an android app which connects to a raspberry pi acting as an access point. The phone connects to the access point like this:

String SSID = "Alarm";
String pass = "Alarm123"
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + SSID + "\"";
conf.preSharedKey = "\"" + pass + "\"";

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

if(!wifiManager.isWifiEnabled()) {
    wifiManager.setWifiEnabled(true);
}

int netId = wifiManager.addNetwork(conf);

wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

And this works just fine. After this, the phone needs to broadcast an UDP packet to the network, which I did like this:

try {
    DatagramSocket socket = new DatagramSocket();
    socket.setBroadcast(true);
    byte[] message = "013A2610E3882D08".getBytes();
    DatagramPacket packet = new DatagramPacket(message, message.length, InetAddress.getByName("255.255.255.255"), 2002);
    socket.send(packet);

    System.out.println("Packet sent");
    socket.close();

}  catch (IOException e) {
    e.printStackTrace();

}

The problem is that the packet is not received where I need to receive it when mobile data is enabled on the phone. I think that this is caused by the fact that the access point from the raspberry pi does not have internet access, so mobile data stays enabled as well, and the packets are sent to the mobile connection instead of the wifi network. When I disable mobile data, it does work.

I looked for a way to disable mobile data programmatically but I found this is no longer possible as of Android 4.4.

I could of course show a prompt asking the user to disable mobile data, but I'd rather find a way to broadcast the packet to the wifi network instead of the mobile network, even though both are enabled. Is there a way to do this?

I'm not sure if I understand your question, but you should be able to bind the socket to the address associated with the wifi adapter before sending the broadcast packet. That way the kernel would know which interface to use when sending the packet.

I'm pretty sure this is how POSIX sockets expose this functionality. I've certainly done similar things in under Linux in C. I've not tried in Android, but it'll end up using the same kernel interfaces so feel pretty confident saying this is what you should be looking for.

This assumes the mobile device is actually connected to that wifi network. You should be able to check in a debugger, or maybe use ifconfig or ip in a shell on the mobile device.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM