Read the IP address of an Android device using DOTNET MAUI

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://acaliaro.wordpress.com/2023/06/06/read-the-ip-address-of-an-android-device-using-dotnet-maui/

Since the days of Windows CE, if I remember correctly, I’ve always used what DOTNET offered me to retrieve the IP address of a device. This code has always worked on Android devices as well:

ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString();

Now, with the advent of DOTNET MAUI and .NET 7, this code seems to break, and always returns “127.0.0.1”. To retrieve the IP address on an Android device in DOTNET MAUI, we can use the Android classes:Now, with the advent of DOTNET MAUI and .NET 7, this code seems to break, and always returns “127.0.0.1”. To retrieve the IP address on an Android device in DOTNET MAUI, we can use the Android classes:

#if ANDROID
                WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Service.WifiService);
                int ipaddress = wifiManager.ConnectionInfo.IpAddress;

                IPAddress ipAddr = new IPAddress(ipaddress);


                //  System.out.println(host);  
                return ipAddr.ToString();
#endif

With the following namespaces:

#if ANDROID
using Android.App;
using Android.Net.Wifi;
#endif

Let’s remember to insert the following permission in the AndroidManifest.xml:

	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Tested on a Zebra TC52 Android 11 device; it seems to work!