42

How can I get gateway and subnet mask details in Android?

AeroX
  • 3,387
  • 2
  • 25
  • 39
Arun Abraham
  • 4,011
  • 14
  • 54
  • 75

8 Answers8

81

I have found a class called DhcpInfo within the android.net package. It has some public variables that stores the values of current Network parameters. But the problem is they return the value in integer converted from 8Bit shifted binary.

Sample Image Describing thee Scenario:

enter image description here

****Here is a sample code:**

**java file:****

package com.schogini.dhcp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.net.*;
import android.net.wifi.WifiManager;

public class dhcpInfo extends Activity {
    public String   s_dns1 ;
    public String   s_dns2;     
    public String   s_gateway;  
    public String   s_ipAddress;    
    public String   s_leaseDuration;    
    public String   s_netmask;  
    public String   s_serverAddress;
    TextView info;
    DhcpInfo d;
    WifiManager wifii;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE);
        d=wifii.getDhcpInfo();

        s_dns1="DNS 1: "+String.valueOf(d.dns1);
        s_dns2="DNS 2: "+String.valueOf(d.dns2);    
        s_gateway="Default Gateway: "+String.valueOf(d.gateway);    
        s_ipAddress="IP Address: "+String.valueOf(d.ipAddress); 
        s_leaseDuration="Lease Time: "+String.valueOf(d.leaseDuration);     
        s_netmask="Subnet Mask: "+String.valueOf(d.netmask);    
        s_serverAddress="Server IP: "+String.valueOf(d.serverAddress);

        //dispaly them
        info= (TextView) findViewById(R.id.infolbl);
        info.setText("Network Info\n"+s_dns1+"\n"+s_dns2+"\n"+s_gateway+"\n"+s_ipAddress+"\n"+s_leaseDuration+"\n"+s_netmask+"\n"+s_serverAddress);
    }
}

xml Coding:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.schogini.dhcp"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".dhcpInfo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
</manifest>

I tried converting the integer value to its equivalent but i couldn't. If you do so you can post back.. Bye..

UPDATE: Some how managed to convert the IP to v4 Format from the integer form Conversion to IPv4 Format:

public String intToIp(int i) {

   return ((i >> 24 ) & 0xFF ) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ( i & 0xFF) ;
}

IMAGE Courtesy: http://www.bennadel.com/blog/1830-Converting-IP-Addresses-To-And-From-Integer-Values-With-ColdFusion.htm

Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • Should you not use the `>>>` operator instead of `>>` – Martin Jun 13 '12 at 07:43
  • 6
    For some reason, the subnet mask seems to be the other way round, i.e. `0.255.255.255` instead of `255.255.255.0` in my case. – Czechnology Jul 31 '13 at 14:53
  • 1
    @Czechnology you can use `Formatter.formatIpAddress( – Simon Dorociak Aug 08 '13 at 06:52
  • Please note that the DhcpInfo class is deprecated as of API 18: https://developer.android.com/reference/android/net/DhcpInfo.html Already had some of my apps crash on me because of this. – Schoentoon Sep 05 '13 at 13:10
  • 3
    @Schoentoon And this class is marked as undepricated in API 19. – GrAnd Apr 30 '14 at 14:10
  • @GrAnd Well that seems odd.. (Not saying you're wrong of course). I should probably see if the issues I had with this on API18 are no longer there with API19. – Schoentoon Apr 30 '14 at 14:19
  • 1
    Yes, that's strange. Goggle says that for [API 18](http://developer.android.com/sdk/api_diff/18/changes/android.net.DhcpInfo.html) it's deprecated. But for [API 19](http://developer.android.com/sdk/api_diff/19/changes/android.net.DhcpInfo.html) it's not deprecated anymore. – GrAnd Apr 30 '14 at 18:33
  • Internally in class DhcpInfo's private method `putAddress` the following code is used for the transformation from `intAsIp` to String: `NetworkUtils.intToInetAddress(addr).getHostAddress()`. But class `NetworkUtils` seems not to be part of the public API. – user1364368 Jul 06 '14 at 08:50
  • Why the ip address would be transferred into 0.0.255.255 – Alston Jul 24 '14 at 14:20
  • @Czechnology Do you know why is that? The same error happens here. – Alston Jul 25 '14 at 02:34
  • Hey, Please try solution provided by @rtc11 – Anoop Chandrika HarisudhanNair Jul 25 '14 at 06:29
  • @AndroidKid is right. now it works. i edited the post (waiting for approval) – Gaucho Feb 15 '15 at 13:30
  • +1 for the answer.Code is worked for me. But how to know ip is static or DHCP ? i changed DNS setting programatically and i want to restore the previous setting? how can we save current setting ? – Harshal Bhatt Nov 30 '15 at 10:07
  • Its be a real crush on me that I couldnot figure out for ethernet as you did **d=wifii.getDhcpInfo();** how can I get dhcp ifo for connected ethernet? – A_rmas May 25 '16 at 11:47
  • 3
    netmask returns 0 always when on Lollipop.. any solution for this..? – Sagar D Feb 16 '17 at 11:58
  • @SagarD I had this problem. I used terminal command for get net mask. i run this code: `process = Runtime.getRuntime().exec("ifconfig wlan0"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));` then extract net mask from string. – mohamad jalali May 31 '20 at 11:33
  • 1
    I want to convert 24 to subnet mask address, which should be 255.255.255.0, but using the method you provided it converts 24 to 0.0.0.24 which is not expected. Also, JAVA only supports 'signed' integers, your example shows 'int', so how is integer representation of 255.255.255.0 would fit in signed-int ? – Akoder Jul 22 '20 at 11:32
  • Hi @Akoder, you found any way to do it ? – karanatwal.github.io Oct 13 '20 at 07:33
  • Hi @karanatwal.github.io – Akoder Oct 14 '20 at 13:52
  • 1
    Hi @karanatwal.github.io I was able to do it, it's in two steps. First we should convert prefixLength to NetmaskInt. Let's say we have prefixLength = 24. 1) Use below method to get netmaskInt: `int netmaskInt = Inet4AddressUtils.prefixLengthToV4NetmaskIntHTH(24);` 2) Pass the netmaskInt to below method: `public static String convertIntToIpString(int netmaskInt) { return ((netmaskInt >> 24) & 0xFF) + "." + ((netmaskInt >> 16) & 0xFF) + "." + ((netmaskInt >> 8) & 0xFF) + "." + (netmaskInt & 0xFF); }` Thid should give you expected result : 255.255.255.0 – Akoder Oct 14 '20 at 14:04
14

Formatter.formatIpAddress(int) is deprecated, and we dont want to use deprecated methods do we?

AndroidKid's version of this is somehow reversed, but this should fix it:

public String intToIp(int addr) {
    return  ((addr & 0xFF) + "." + 
            ((addr >>>= 8) & 0xFF) + "." + 
            ((addr >>>= 8) & 0xFF) + "." + 
            ((addr >>>= 8) & 0xFF));
}

Source: http://www.devdaily.com/java/jwarehouse/android/core/java/android/net/DhcpInfo.java.shtml

rtc11
  • 747
  • 8
  • 23
  • Maybe it would be a bit more efficient to use _StringBuffer_ instead of six string concatenations with operator _"+"_ (for the latter on each concatenation the previous String-object is discarded and a new String-object is created), see [_this gist_](https://gist.github.com/mide42/a19c53799423804940d4). – user1364368 Jul 11 '14 at 07:32
  • 1
    The compiler will actually create a stringbuffer and append the strings in this case. So it doesnt matter. If you however uses the method in iterations like: for(int i = 0; i<10; i++) intToIp(addr[i]); Then it will create six times ten strings. – rtc11 Jul 29 '14 at 12:06
5

This is an old Thread, but I found the official function used by android API (package android.net.NetworkUtils):

/**
 * Convert a IPv4 address from an integer to an InetAddress.
 * @param hostAddress an int corresponding to the IPv4 address in network byte order
 */
public static InetAddress intToInetAddress(int hostAddress) {
    byte[] addressBytes = { (byte)(0xff & hostAddress),
                            (byte)(0xff & (hostAddress >> 8)),
                            (byte)(0xff & (hostAddress >> 16)),
                            (byte)(0xff & (hostAddress >> 24)) };

    try {
       return InetAddress.getByAddress(addressBytes);
    } catch (UnknownHostException e) {
       throw new AssertionError();
    }
}

And once you have InetAddress you can get the formatted String this way:

intToInetAddress(d.gateway).getHostAddress()

M1n1_Z
  • 74
  • 1
  • 4
5

to format the ip, try using:

import android.text.format.Formatter;

public String FormatIP(int IpAddress)
{
    return Formatter.formatIpAddress(IpAddress);
}
Goldeneye
  • 75
  • 1
4

Use Formatter.formatIpAddress(mask); mask is your int.

String maskk = Formatter.formatIpAddress(mask);
Gabber
  • 5,152
  • 6
  • 35
  • 49
Kostadin Georgiev
  • 866
  • 1
  • 9
  • 23
3

This version works with any Network (Wifi/Cell). Returns V4 and V6.

/**
 * Returns the set of all gateways<V4 & V6> for any Network
 *
 */
fun getGatewaySet(network:Network, context:Context):MutableSet<InetAddress> {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    connectivityManager.getLinkProperties(network)?.routes?.let {
        //Saw dupes on my device, so use a set
        val set = mutableSetOf<InetAddress>()
        for (routeInfo in it) {
            routeInfo?.gateway?.let { inetAddress ->
                //If comes from AOSP isGateway() - requires API 29
                if (!inetAddress.isAnyLocalAddress) {
                    set.add(inetAddress)
                }
            }
        }
        return set
    }
    return Collections.EMPTY_SET as MutableSet<InetAddress>
}
Dustin
  • 2,064
  • 1
  • 16
  • 12
2

Instead of getting 255.255.255.0, just change the order in return ;) So you will be able to get in the right order...

public String intToIp(int i) {

   return (i & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 24 ) & 0xFF) ;
}
-2

Although old, works like a charm.

tvGateway.setText(Formatter.formatIpAddress(dhcpInfo.gateway));