Get / Set IPv4 Address for Android

I need a simple helper class to do these tasks on API 18 and up:

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

2- set / get dhcp ip address for 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 found various solutions for this, but some of the methods are outdated and I am confused, the witch-solution is better. Can anyone help me populate the methods in a better and more standard way?

+3


source to share


1 answer


This SO thread won't help you get getDhcpIpV4Parameters

?

My Utils method / code for getting 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;
    }

      

0


source







All Articles