How to Obtain the Connection Information Programmatically in Android?

14 Oct, 2020
Sometimes it becomes challenging to find the network-related details, especially the device’s IP address, which could be needed to grant unique preferences through the modem software. Because of the variance in the information shown to the user across multiple Android devices (Samsung, Mi, Lava), we implemented an application through which the details regarding the current network could be fetched easily and available in one place. The information or the entities regarding the connection that we extracted from the device in our program were:
IP Address: It is a numerical label delegated to every device connected that is connected to a network that uses the Internet Protocol for communication.Link Speed: It is the maximum achievable speed (in Bits per second) that the device can communicate with the other on the same network.Network ID: It is the portion of an IP address on which a host resides. It identifies the TCP/IP networkSSID (Service Set Identifier): is a unique ID consisting of 32 characters that are used for wireless network naming.Hidden SSID: Same as SSID. Hiding the SSID an efficient way of securing the network. This prevents the network from showing up in the list of available Wi-Fi networks when people scan for nearby Wi-Fi connections.BSSID: The SSID keeps the packets within the correct WLAN. The packets are safe even when overlapping WLANs are present. Nevertheless, there are multiple access points within every WLAN. Basic Service Set Identifier (BSSID) identifies those access points and the associated clients and is included in all wireless packets.
IP Address: It is a numerical label delegated to every device connected that is connected to a network that uses the Internet Protocol for communication.
Link Speed: It is the maximum achievable speed (in Bits per second) that the device can communicate with the other on the same network.
Network ID: It is the portion of an IP address on which a host resides. It identifies the TCP/IP network
SSID (Service Set Identifier): is a unique ID consisting of 32 characters that are used for wireless network naming.
Hidden SSID: Same as SSID. Hiding the SSID an efficient way of securing the network. This prevents the network from showing up in the list of available Wi-Fi networks when people scan for nearby Wi-Fi connections.
BSSID: The SSID keeps the packets within the correct WLAN. The packets are safe even when overlapping WLANs are present. Nevertheless, there are multiple access points within every WLAN. Basic Service Set Identifier (BSSID) identifies those access points and the associated clients and is included in all wireless packets.
Unfortunately, a few entities, such as the MAC Address, could not be fetched correctly, and there is a genuine reason.
MAC addresses are globally unique, which makes every other device unique from the other. This label is not user-resettable and survives factory resets. Therefore, it is not preferred to identify the users uniquely.
From Android 6.0 (API 23) and Android 9 (API 28), local device MAC addresses, such as Bluetooth and Wi-Fi, are not available through the third-party APIs.
The WifiInfo.getMacAddress() method and the BluetoothAdapter.getDefaultAdapter().getAddress() method both by default return 02:00:00:00:00:00.
Additionally, between Android 6 and Android 9, the following permissions must be held to access MAC addresses of nearby external devices which are available through Bluetooth and Wi-Fi scans:
Method/Property Permissions Required: ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
To obtain the current connection information in Android, we shall follow the following steps. Note that we are going to implement this project using the Kotlin language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the AndroidManifest.xml file
Go to the AndroidManifest.xml file and add these uses-permissions: ACCESS_WIFI_STATE, ACCESS-FINE-LOCATION, and ACCESS_COARSE_LOCATION.
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/>
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/>
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
Below is the completed for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="org.geeksforgeeks.connectioninfo">        <!--Add these permissions-->    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>      <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>  </manifest>
Step 3: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application, and create a TextView where we would broadcast the information from the MainActivity.kt file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <!--A TextView to display all the fetched information-->    <TextView        android:id="@+id/wifiInfo"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true" />  </RelativeLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.annotation.SuppressLintimport android.content.Contextimport android.net.wifi.WifiManagerimport android.os.Bundleimport android.text.format.Formatterimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity  class MainActivity : AppCompatActivity() {      @SuppressLint("SetTextI18n")    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Invoking the Wifi Manager        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager        // Method to get the current connection info        val wInfo = wifiManager.connectionInfo          // Extracting the information from the received connection info        val ipAddress = Formatter.formatIpAddress(wInfo.ipAddress)        val linkSpeed = wInfo.linkSpeed        val networkID = wInfo.networkId        val ssid = wInfo.ssid        val hssid = wInfo.hiddenSSID        val bssid = wInfo.bssid          // Finding the textView from the layout file        val wifiInformationTv = findViewById<TextView>(R.id.wifiInfo)          // Setting the text inside the textView with        // various entities of the connection        wifiInformationTv.text =              "IP Address:\t$ipAddress\n" +                    "Link Speed:\t$linkSpeed\n" +                    "Network ID:\t$networkID\n" +                    "SSID:\t$ssid\n" +                    "Hidden SSID:\t$hssid\n" +                    "BSSID:\t$bssid\n"    }}
Note: The following program requires the device to have an active connection. Kindly connect to Wi-Fi. Failing to do so would fetch nothing.
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.