3

I need a simple helper class to do these jobs on API 18 and above:

1- set / get static ip address for the device.

2- set / get dhcp ip address for the device.

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() {
        ...
    }
}

I've found different solutions to do this but some methods has deprecated and I'm confused witch solution is better. Can somebody help me to fill the methods with the best and more standard way?

Ahmad Behzadi
  • 1,006
  • 15
  • 30

1 Answers1

0

This SO thread does not help you to get getDhcpIpV4Parameters?

My Utils method/code to retrieve the FIRST IPV4 address I found is:

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;
    }
Community
  • 1
  • 1
r.pedrosa
  • 709
  • 5
  • 12
  • The above **SO** that you linked uses `getDhcpInfo` that has been deprecated. – Ahmad Behzadi May 13 '15 at 09:30
  • What about get static subnet , gateway , dns ? How can I set them? – Ahmad Behzadi May 13 '15 at 09:31
  • 1
    For the subnet you can use [this SO thread](http://stackoverflow.com/questions/1221517/how-to-get-subnet-mask-of-local-system-using-java). Just use `intf ` variable to get the list of InterfaceAddress. – r.pedrosa May 13 '15 at 10:03