Returns the broadcast address used on the current WIFI network. - Android Network

Android examples for Network:Network Status

Description

Returns the broadcast address used on the current WIFI network.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.net.InetAddress;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;

public class Main {
    /**/*  ww w .j a  v a  2 s. c o  m*/
     * Returns the broadcast address used on the current WIFI network.
     * 
     * @param context
     *            Application context needed to access the WIFI service.
     * @return InetAdress for broadcasts
     * @throws IOException
     */
    public static InetAddress getBroadcastAddress(Context context)
            throws IOException {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);

        // Throw if no WifiManager available
        if (wifi == null) {
            throw new IOException(
                    "NULL WifiManager. You must be connected to a wifi network.");
        }

        DhcpInfo dhcp = wifi.getDhcpInfo();
        // If the dhcp info is null, just return the default broadcast address.
        if (dhcp == null) {
            return InetAddress.getByName("255.255.255.255");
        }
        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) & 0xFF);
        return InetAddress.getByAddress(quads);
    }
}

Related Tutorials