views:

298

answers:

1

Hey,

I am making a Client Server application for my Android phone.

I have created a UDP Server in Python which sits and listens for connections.

I can put either the server IP address in directly like 192.169.0.100 and it sends data fine. I can also put in 192.168.0.255 and it find the server on 192.169.0.100.

Is it possible to get the broadcast address of the network my Android phone is connected to? I am only ever going to use this application on my Wifi network or other Wifi networks.

Cheers

A: 

As the broadcast IP address is the current IP address but finishing with 255, you can do something like this:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf
                    .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {}
    return null;
}

public String getBroadcastIP(){
    String myIP = getLocalIpAddress();
    StringTokenizer tokens = new StringTokenizer(myIP, ".");
    int count = 0;
    String broadcast = "";
    while (count < 3) {
        broadcast += tokens.nextToken() + ".";
        count++;
    }
    return broadcast+"255";
}
Cristian
That's making the (possibly unwarranted) assumption that the netmask is 255.255.255.255. You should actually get the netmask associated with the address that you retrieved, and then compute `bcast = ipAddress | ~netmask`
hobbs
I was thinking that, how would you implement such a thing? Cheers
Eef