3

我需要一个简单的辅助类来在 API 18 及更高版本上完成这些工作:

1- 设置/获取设备的静态 IP 地址。

2- 设置/获取设备的 dhcp ip 地址。

public static class IPv4Helper {
    public static class ipV4Parameters {
        String ipAddress;
        String subnetMask; // or int
        String defaultGateway;
        String dns1;
        String dns2;
    }

    public static boolean isDhcpEnabled() {
        ...
        if (current_wifi_is_on_DHCP)
            return true;
        else
            return false;
    }

    public static ipV4Parameters getStaticIpV4Parameters() {
        ...
    }

    public static ipV4Parameters getDhcpIpV4Parameters() {
        ...
    }
    public static boolean setStaticIpV4Address(ipV4Parameters newStaticAddress) {
        ...
    }
    public static boolean setDhcpEnabled() {
        ...
    }
}

我找到了不同的解决方案来做到这一点,但有些方法已被弃用,我很困惑女巫解决方案更好。有人可以帮助我用最好和更标准的方式填充这些方法吗?

4

1 回答 1

0

这个 SO 线程不能帮助你得到getDhcpIpV4Parameters吗?

我的 Utils 方法/代码来检索我找到的第一个 IPV4 地址是:

public static String getStaticIpV4Address() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    // for getting IPV4 format
                    String ipv4; //= inetAddress.getHostAddress().toString();
                    if ( (!inetAddress.isLoopbackAddress()) 
                            && (InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) ) {
                        return ipv4;
                    }
                }
            }
        } catch (SocketException ignored) {}

        return null;
    }
于 2015-05-13T09:11:22.607 回答