1. 程式人生 > >Xamarin.Forms 獲取裝置的ip地址

Xamarin.Forms 獲取裝置的ip地址

So I have been working on an Enterprise level cross platform mobility project since last year, whereas I have been initially using pure Xamarin.Forms cross platform for the entire project.
And recently my boss gave me a requirement of retrieving the IP Address of the mobile device where the user has installed the App. So I straightaway looked for libraries which I could use just to retrieve the IP address, but unfortunately I couldn’t find, even though I came across this 

Mobile Service Plugins for Xamarin.Forms which actually didn’t work properly in case of retrieving IP address when I implemented it. So while the clock was ticking I decided to write the code from scratch and successfully implemented the feature, tested out in all three mobile platforms in just 30 mins. :D
 (yeeeei :P )

When I was writing the code, I couldn’t find any proper tutorial for accessing the network services and retrieving the IP address, which was kinda disappointing. So I thought of sharing the code I wrote with you fellow awesome Xamarin Developers. (I’m gonna assume that you are already aware of 

DependencyService in Xamarin.Forms platform ;) )

This piece of code which acts as the interface for the IPAddressManager goes in your PCL project.

namespace YourAppNamespace.Services
{
    public interface IIPAddressManager
    {
        String GetIPAddress();
    }
}

This is the code for your Windows Phone project,

[assembly: Dependency(typeof(YourAppNamespace.WinPhone.WinPhone.DependencyServices.IPAddressManager))]

namespace YourAppNamespace.WinPhone.WinPhone.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public string GetIPAddress()
        {
            try
            {
                List<string> IpAddress = new List<string>();
                var Hosts = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().ToList();
                foreach (var Host in Hosts)
                {
                    string IP = Host.DisplayName;
                    IpAddress.Add(IP);
                }

                IPAddress address = IPAddress.Parse(IpAddress.Last());

                return address.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

This is the code for your iOS project,

[assembly: Dependency(typeof(YourAppNamespace.iOSUnified.iOS.DependencyServices.IPAddressManager))]

namespace YourAppNamespace.iOSUnified.iOS.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public string GetIPAddress()
        {
            String ipAddress = "";

            foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                    netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipAddress = addrInfo.Address.ToString();

                        }
                    }
                }
            }

            return ipAddress;
        }
    }
}

And finally this is the code for your Android project,

[assembly: Dependency(typeof(YourAppNamespace.Android.Android.DependencyServices.IPAddressManager))]

namespace YourAppNamespace.Android.Android.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public string GetIPAddress()
        {
            IPAddress[] adresses = Dns.GetHostAddresses(Dns.GetHostName());

            if (adresses !=null && adresses[0] != null)
            {
                return adresses[0].ToString();
            }
            else
            {
                return null;
            }
        }
    }
}

Well well thats it. Now go ahead and call that GetIPAddress() method in wherever you want and retrieve the IP address of the mobile device where your apps is installed in. ;)

// Retrieving IP Address in Runtime...

string ipaddress = DependencyService.Get<IIPAddressManager>().GetIPAddress

Oh btw when you compile and run the code, make sure the mobile device is connected to the Internet so that the mobile device will sure be assigned with an IP Address. ;)

Have fun, fellow awesome Xamarin geeks ! :D