2

I want to broadcast from an android device which acts as a hotspot, but using 255.255.255.255 does not work as UDP broadcast in android. But 192.168.1.255 this broadcast address works. When I check the IP address of my device its shows 192.168.1.4.

Now how to calculate address 192.168.1.255 from this address?

5
  • stackoverflow.com/questions/2993874/android-broadcast-address Commented Dec 7, 2012 at 8:19
  • yes i tried to dhcp but its returning null because its acting as dhcp server Commented Dec 7, 2012 at 8:21
  • i mean the forum, not the app for root Commented Dec 7, 2012 at 8:21
  • @323go, yes mate you are right Commented Dec 7, 2012 at 8:25
  • You cannot calculate a broadcast address from the IP address alone. You must know the netmask as well. Commented Dec 8, 2012 at 4:29

1 Answer 1

3

Well, if you have the broadcasting worked out and only need to change the last byte of the address to 255, you can do the following:

String getBroadcastAddress( final String address ) throws UnknownHostException { InetAddress addr = InetAddress.getByName( address ); if( InetAddress instanceof Inet4Address ) { byte[] bytes = addr.getAddress(); bytes[3] = 255; return InetAddress.getByAddress( bytes ).getHostAddress(); } else { ... deal with ipv6 } } 

Pulling the broadcast address directly from the NetworkInterface, results in this code:

public static String getBroadcast() throws SocketException { System.setProperty("java.net.preferIPv4Stack", "true"); for( Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { NetworkInterface nif = interfaces.nextElement(); if( !nif.isLoopback() ) { for( InterfaceAddress addr : nif.getInterfaceAddresses() ) { return addr.getBroadcast().toString().substring(1); } } } return null; } 

You may have to sift through the NetworkInterface to find the one corresponding to the internal ip.

Sign up to request clarification or add additional context in comments.

4 Comments

But its not necessary that only last byte will be need to change..I am developing the general application fro all android phones.So we cant say that only last byte can be useful.Anyways thnx for helping me
You cannot assume the device is on a class C subnet! It has nothing to do with the device really. This answer is incorrect.
The question title: "How to get the subnet mask of my android device which acts as a hotspot?" From the first sentence: "I want to broadcast from an android device" The intent is clear, despite the error made in the last sentence of the question. Your answer is not sufficient.
@Brad, you win the internets. In the meantime, I extended the answer to work universally.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.