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
The broadcast address is always identified in the final part of the host part of an address (starts in the third or fourth octet): If all host bits are set to the binary value “1”, this is the broadcast address. If all host bits are set to the value “0”, this is the subnet address. 192.128.
A broadcast address is an IP address that is used to target all systems on a specific subnet network instead of single hosts. In other words broadcast address allows information to be sent to all machines on a given subnet rather than to a specific machine.
Determine the broadcast address for your IP address. The lowest address of the subnet your IP address falls in is the network address. The highest address in the subnet your IP address falls in is the broadcast address. Our example IP address 210.1. 1.100 falls in the 210.1.
Broadcast addresses are usually formed by setting the “host address” portion of the IP address to 1, which is the default for the router and most modern computer systems. Some old systems may form the broadcast address by setting the host portion to 0, and may be incapable of using the “1” form.
From
http://code.google.com/p/boxeeremote/source/browse/trunk/Boxee+Remote/src/com/andrewchatham/Discoverer.java?spec=svn28&r=28
private InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) (broadcast >> (k * 8));
return InetAddress.getByAddress(quads);
}
This has the advantage of only looking at WIFI. I know OP said "I am only ever going to use this application on my Wifi network or other Wifi networks." but it's worth mentioning this in case someone else needs a non-wifi alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With