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

相关说明: ConsoleApplication1_sERVER ----PC-服务端 MyNetTest --------------------IOS-客户端 1、PC-服务端 只是一个运行在windows系统下的 控制台程序。接收来自客户端的信息。 2、IOS-客户端 运行在ios模拟器上,连接PC服务端的ip,发生相关信息。 3、两台主机,一台是运行windows系统的计算机。另外一台是MacBook计算机。运行ios模拟器。 4、pc-服务端,可以用vs2008打开并且编辑。 5、ios客户端,使用的是XamarinStudio 打开并且编辑。 以下是这个例子中的特别提到的地方 A、这个例子是完全用C#写的。 B、ios由于是伪后台,当程序退回到后台,系统留给程序的可运行时间就只有3分钟。 过了3分钟,就会把这个程序的所有线程挂起(当然内部预留了长任务运行这一后招)。 经过多次试验后,可以借助着3分钟的长任务运行,然后通过简单的修改来突破这个界限。 在本例子中,所有线程共享一个线程ID。 其中只需要一条线程负责不停的延长这个线程ID的运行时间,然后其他的线程就只需要专注于其本应该要做的任务即可。 C、本例子中,还实现了另外一个功能,就是ios程序与PC程序进行socket。当然是最为简单的。 ---------------- 由于本人也是刚刚使用c#开发ios程序,初入门,为了这两个问题,也是研究了很久,可查的资料又很少。 希望能够帮助到同样遇到困难的你。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值