Obtain IP address from host name on Android using Xamarin

Simon Quin 1 Reputation point
2021-04-06T08:11:12.48+00:00

I wrote an app using WinForms in C#, part of which was to access a device on my local network using its name rather than IP address. This used the function Dns.GetHostEntry() which works as expected. I then created an Android application using Xamarin forms and found that this function is not supported. What is the recommended method of obtaining the IP address from the host name on this platform?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,362 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,008 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 76,546 Reputation points Microsoft Vendor
    2021-04-06T10:52:25.067+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    For get IP address in Android, you can create a dependenceService in PCL.

       public interface INetServices  
           {  
               string ConvertHostIP();  
           }  
    

    Then achieve this interface in the android folder.

       using System.Collections.Generic;  
       using System.Linq;  
       using System.Net;  
       using System.Text;  
       using Xamarin.Forms;  
         
       [assembly: Dependency(typeof(NetService))]  
       namespace MultilingualXFSample.Droid  
       {  
           class NetService: INetServices  
           {  
         
               public string ConvertHostIP()  
               {  
                   WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Service.WifiService);  
                   int ip = wifiManager.ConnectionInfo.IpAddress;  
         
                   IPAddress ipAddr = new IPAddress(ip);  
         
                  
                 //  System.out.println(host);  
                   return ipAddr.ToString();  
               }  
           }  
       }  
    

    And add following permission in the AndroidManifest.xml

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

    In the Xamarin forms, you can get IP address like following code.

       string IPAddress= DependencyService.Get<INetServices>().ConvertHostIP();  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.