[Android]获取局域网广播地址的两种方法

来源:互联网 发布:软件如何申请著作权 编辑:程序博客网 时间:2024/05/17 01:12

第一种是自己写的,有一些bug,不过凑合着用也可以,第二种是stackoverflow的,推荐用这种。

(1)

private InetAddress calcBroadcastAddress(InetAddress mask, InetAddress ip)throws IOException {int ipaddress = getIntAddress(ip);int maskaddress = getIntAddress(mask);int broadcast = ipaddress & maskaddress | ~maskaddress;byte[] quads = new byte[4];for (int k = 0; k < 4; k++) {quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);}return InetAddress.getByAddress(quads);}private InetAddress getBroadcastAddress() throws IOException {// 自动获取String strIp = getCommandResult("/system/bin/getprop","dhcp.eth0.ipaddress");String strMask = getCommandResult("/system/bin/getprop","dhcp.eth0.mask");if (!strIp.equals("\n")) {InetAddress mask = InetAddress.getByName(strMask);InetAddress ip = InetAddress.getByName(strIp);Log.v("ws-discovery", "auto ip:" + strIp);return calcBroadcastAddress(mask, ip);} else {// 手动配置String strManual = getCommandResult("/system/bin/ifconfig", "eth0");String[] netInfo = strManual.split(" ");if (netInfo.length >= 5) {InetAddress mask = InetAddress.getByName(netInfo[4]);InetAddress ip = InetAddress.getByName(netInfo[2]);Log.v("ws-discovery", "manual ip:" + netInfo[2]);return calcBroadcastAddress(mask, ip);}}// wifiWifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);DhcpInfo dhcp = wifi.getDhcpInfo();Log.v("ws-discovery", "wifi ip:" + Integer.toString(dhcp.ipAddress));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);}private int getIntAddress(InetAddress address) {byte[] addrs = address.getAddress();int addr = 0;addr = ((addrs[3] & 0xff) << 24) | ((addrs[2] & 0xff) << 16)| ((addrs[1] & 0xff) << 8) | (addrs[0] & 0xff);return addr;}private String getCommandResult(String commands, String args) {Process process = null;String inet = null;try {process = new ProcessBuilder().command(commands, args).redirectErrorStream(true).start();InputStream in = process.getInputStream();int count = 0;while (count == 0) {count = in.available();}byte[] b = new byte[count];in.read(b);inet = new String(b);} catch (IOException e) {e.printStackTrace();} finally {if (process != null)process.destroy();}return inet;}


(2)

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