Pal Szasz
Pal Szasz

Reputation: 3225

What is the best way to get a broadcast address from an ip address?

I'm writing an android application which should send out broadcast packets over WiFi.

Currently I can get the IP address of the device from WifiManager.getConnectionInfo().getIpAddress() and guess the broadcast address by simply replacing the last digit with 0. But I really don't like this solution.

What would be the proper way?

Upvotes: 1

Views: 4254

Answers (2)

Anup Cowkur
Anup Cowkur

Reputation: 20553

Try something like this:

    public static String getBroadcast(){
    String found_bcast_address=null;
     System.setProperty("java.net.preferIPv4Stack", "true"); 
        try
        {
          Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
          while (niEnum.hasMoreElements())
          {
            NetworkInterface ni = niEnum.nextElement();
            if(!ni.isLoopback()){
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses())
                {

                  found_bcast_address = interfaceAddress.getBroadcast().toString();
                  found_bcast_address = found_bcast_address.substring(1);

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

        return found_bcast_address;
}

Upvotes: 2

Luis
Luis

Reputation: 12048

You need to replace with 255 not with 0.

If you are targeting SDK 9 or later you can use getBroadcast(), otherwise you need to overide the numbers in IP address.

Example code:

public static InetAddress getNetworkLocalBroadcastAddressdAsInetAddress() throws IOException {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();
        if(VERSION.SDK_INT < 9) { 
            if(!intf.getInetAddresses().nextElement().isLoopbackAddress()){
                byte[] quads = intf.getInetAddresses().nextElement().getAddress();
                quads[0] = (byte)255;
                quads[1] = (byte)255;
                return InetAddress.getByAddress(quads);
            }
        }else{
            if(!intf.isLoopback()){
                List<InterfaceAddress> intfaddrs = intf.getInterfaceAddresses();
                return intfaddrs.get(0).getBroadcast(); //return first IP address
            }
        }
    }
    return null;
}

Upvotes: -1

Related Questions