xamarin android,UWP 网络类型和IP地址

 App开发经常要判断网络连通情况,并判断网络类型,获取网络IP。xamarin中可以使用Dependencies提供各平台下的方法,现把各平台代码记录如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 using Android.App;
  7 using Android.Content;
  8 using Android.OS;
  9 using Android.Runtime;
 10 using Android.Views;
 11 using Android.Widget;
 12 using Xamarin.Forms;
 13 using Test.Droid.Dependencies;
 14 using Android.Net;
 15 using Test.Dependencies;
 16 using Java.Net;
 17 using Java.Util;
 18 using Android.Telephony;
 19 using Android.Net.Wifi;
 20 using Org.Apache.Http.Conn.Util;
 21 
 22 [assembly: Dependency(typeof(NetworkStatusAndroid))]
 23 namespace Test.Droid.Dependencies
 24 {
 25     public class NetworkStatusAndroid : INetworkStatus
 26     {
 27         public bool HasNetwork()
 28         {
 29 
 30             //Test();
 31 
 32             ConnectivityManager cwjManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Context.ConnectivityService);
 33             bool hasNetwork = true;
 34             if (cwjManager.ActiveNetworkInfo != null)
 35             {
 36                 hasNetwork = cwjManager.ActiveNetworkInfo.IsAvailable;
 37             }
 38             else
 39             {
 40                 hasNetwork = false;
 41             }
 42 
 43             return hasNetwork;
 44         }
 45         public string GetNetType()
 46         {
 47             return getCurrentNetType(Android.App.Application.Context);
 48         }
 49 
 50         /// <summary>
 51         /// 获取网络类型
 52         /// </summary>
 53         /// <param name="context"></param>
 54         /// <returns></returns>
 55         public static string getCurrentNetType(Context context)
 56         {
 57             String type = "";
 58             ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
 59             NetworkInfo info = cm.ActiveNetworkInfo;
 60             if (info == null)
 61             {
 62                 type = "null";
 63             }
 64             else if (info.Type == ConnectivityType.Wifi)
 65             {
 66                 type = "wifi";
 67             }
 68             else if (info.Type == ConnectivityType.Mobile)
 69             {
 70                 int subType = (int)info.Subtype;
 71                 if (subType == (int)NetworkType.Cdma || subType == (int)NetworkType.Gprs
 72                 || subType == (int)NetworkType.Edge)
 73                 {
 74                     type = "2g";
 75                 }
 76                 else if (subType == (int)NetworkType.Umts || subType == (int)NetworkType.Hsdpa
 77               || subType == (int)NetworkType.EvdoA || subType == (int)NetworkType.Evdo0
 78               || subType == (int)NetworkType.EvdoB)
 79                 {
 80                     type = "3g";
 81                 }
 82                 else if (subType == (int)NetworkType.Lte)
 83                 {// LTE是3g到4g的过渡,是3.9G的全球标准
 84                     type = "4g";
 85                 }
 86             }
 87             return type;
 88         }
 89 
 90         /// <summary>获取手机wifi
 91         /// </summary>
 92         /// <returns></returns>
 93         public string GetWifiIP()
 94         {
 95             string IP = String.Empty;
 96             Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)Forms.Context.GetSystemService(Context.WifiService);
 97             if (wifi.IsWifiEnabled)
 98             {
 99                 Android.Net.Wifi.WifiInfo wifiInfo = wifi.ConnectionInfo;
100                 IP = Mixin.Common.StringFormat.intToIp(wifiInfo.IpAddress);
101             }
102             return IP;
103         }
104 
105         /// <summary>
106         /// 获取手机IP地址
107         /// </summary>
108         /// <returns></returns>
109         public string Test()
110         {
111             IEnumeration ie = NetworkInterface.NetworkInterfaces;
112             while (ie.HasMoreElements)
113             {
114                 NetworkInterface intf = ie.NextElement() as NetworkInterface;
115                 IEnumeration enumIpAddr = intf.InetAddresses;
116                 while (enumIpAddr.HasMoreElements)
117                 {
118 
119                     InetAddress inetAddress = enumIpAddr.NextElement() as InetAddress;
120 
121                     if (!inetAddress.IsLoopbackAddress && (inetAddress as Inet4Address) != null && inetAddress.HostAddress.ToString() != "127.0.0.1")
122                     {
123                         return inetAddress.HostAddress.ToString();
124                     }
125                 }
126             }
127             return null;
128         }
129     }
130 }
Android
  1 using Test.Dependencies;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Threading.Tasks;
  7 using Windows.Networking.Connectivity;
  8 using Xamarin.Forms;
  9 
 10 [assembly: Dependency(typeof(Test.UWP.Dependencies.NetworkStatus))]
 11 namespace Test.UWP.Dependencies
 12 {
 13     public class NetworkStatus : INetworkStatus
 14     {
 15         static string None = "None";
 16         static string Unknown = "Unknown";
 17         static string IIG = "2G";
 18         static string IIIG = "3G";
 19         static string IVG = "4G";
 20         static string Wifi = "wifi";
 21         static string Lan = "Lan";
 22         /// <summary>当前应用是否联网
 23         /// </summary>
 24         /// <returns></returns>
 25         public bool HasNetwork()
 26         {
 27             bool isConnected = false;
 28 
 29             string InternetType = null;
 30             ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
 31             if (profile == null)
 32             {
 33                 InternetType = NetworkStatus.None;
 34             }
 35             else
 36             {
 37                 NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel();
 38                 isConnected = (cl != NetworkConnectivityLevel.None);
 39             }
 40             return isConnected;
 41         }
 42         /// <summary>
 43         /// </summary>
 44         /// <returns></returns>
 45         public string GetWifiIP()
 46         {
 47             var icp = NetworkInformation.GetInternetConnectionProfile();
 48 
 49             if (icp?.NetworkAdapter == null) return null;
 50             var hostname =
 51                 NetworkInformation.GetHostNames()
 52                     .SingleOrDefault(
 53                         hn =>
 54                             hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
 55                             == icp.NetworkAdapter.NetworkAdapterId);
 56 
 57             // the ip address  
 58             return hostname?.CanonicalName;
 59             //return null;
 60         }
 61         /// <summary>
 62         /// 获取UWP连接类型
 63         /// </summary>
 64         /// <returns></returns>
 65         public string GetNetType()
 66         {
 67             bool isConnected = false;
 68 
 69             string InternetType = null;
 70             ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
 71             if (profile == null)
 72             {
 73                 InternetType = NetworkStatus.None;
 74             }
 75             else
 76             {
 77                 NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel();
 78                 isConnected = (cl != NetworkConnectivityLevel.None);
 79             }
 80             if (!isConnected)
 81             {
 82                 return NetworkStatus.None;
 83             }
 84             if (profile.IsWwanConnectionProfile)
 85             {
 86                 if (profile.WwanConnectionProfileDetails == null)
 87                 {
 88                     InternetType = NetworkStatus.Unknown;
 89                 }
 90                 WwanDataClass connectionClass = profile.WwanConnectionProfileDetails.GetCurrentDataClass();
 91                 switch (connectionClass)
 92                 {
 93                     //2G
 94                     case WwanDataClass.Edge:
 95                     case WwanDataClass.Gprs:
 96                         InternetType = NetworkStatus.IIG;
 97                         break;
 98                     //3G
 99                     case WwanDataClass.Cdma1xEvdo:
100                     case WwanDataClass.Cdma1xEvdoRevA:
101                     case WwanDataClass.Cdma1xEvdoRevB:
102                     case WwanDataClass.Cdma1xEvdv:
103                     case WwanDataClass.Cdma1xRtt:
104                     case WwanDataClass.Cdma3xRtt:
105                     case WwanDataClass.CdmaUmb:
106                     case WwanDataClass.Umts:
107                     case WwanDataClass.Hsdpa:
108                     case WwanDataClass.Hsupa:
109                         InternetType = NetworkStatus.IIIG;
110                         break;
111                     //4G
112                     case WwanDataClass.LteAdvanced:
113                         InternetType = NetworkStatus.IVG;
114                         break;
115                     //无网
116                     case WwanDataClass.None:
117                         InternetType = NetworkStatus.Unknown;
118                         break;
119                     case WwanDataClass.Custom:
120                     default:
121                         InternetType = NetworkStatus.Unknown;
122                         break;
123                 }
124             }
125             else if (profile.IsWlanConnectionProfile)
126             {
127                 InternetType = NetworkStatus.Wifi;
128             }
129             else
130             {
131                 ///不是Wifi也不是蜂窝数据判断为Lan
132                 InternetType = NetworkStatus.Lan;
133             }
134             return InternetType;
135         }
136     }
137 }
UWP

IOS的方法还没写全后面不上,先写一部分

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 using Foundation;
  7 using UIKit;
  8 using Test.iOS.Dependencies;
  9 using Xamarin.Forms;
 10 using Test.Dependencies;
 11 using SystemConfiguration;
 12 using System.Net;
 13 using CoreFoundation;
 14 using ObjCRuntime;
 15 
 16 [assembly: Dependency(typeof(NetworkStatusIOS))]
 17 namespace Test.iOS.Dependencies
 18 {
 19     public class NetworkStatusIOS : INetworkStatus
 20     {
 21 
 22         public bool HasNetwork()
 23         {
 24             //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 
 25             System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
 26             bool hasNetWork = false;
 27             NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
 28             NetworkReachabilityFlags flags;
 29             //获得连接的标志 
 30             bool didRetrieveFlags = defaultRouteReachability.TryGetFlags(out flags);
 31             if (!didRetrieveFlags)
 32             {
 33                 hasNetWork = false;
 34             }
 35             //根据获得的连接标志进行判断
 36             bool isReachable = (flags & NetworkReachabilityFlags.Reachable) == NetworkReachabilityFlags.Reachable;
 37             bool needsConnection = (flags & NetworkReachabilityFlags.ConnectionRequired) == NetworkReachabilityFlags.ConnectionRequired;
 38 
 39             hasNetWork = (isReachable && !needsConnection);
 40 
 41             return hasNetWork;
 42         }
 43 
 44         public string GetWifiIP()
 45         {
 46             //SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); //创建测试连接的引用:
 47             System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
 48             NetworkReachabilityFlags flags = NetworkReachabilityFlags.IsLocalAddress;
 49             IsAdHocWiFiNetworkAvailable(out flags);
 50             //NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
 51             //defaultRouteReachability.TryGetFlags
 52 
 53             return "";
 54         }
 55         public string GetNetType()
 56         {
 57             string strNetworkType = "";
 58 
 59             //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 
 60             System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
 61             bool hasNetWork = false;
 62             NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
 63             NetworkReachabilityFlags flags;
 64             //获得连接的标志 
 65             bool didRetrieveFlags = defaultRouteReachability.TryGetFlags(out flags);
 66             if (!didRetrieveFlags)
 67             {
 68                 hasNetWork = false;
 69             }
 70 
 71             if ((flags & NetworkReachabilityFlags.ConnectionRequired) == 0)
 72             {
 73                 strNetworkType = "WIFI";
 74             }
 75             if (
 76                 ((flags & NetworkReachabilityFlags.ConnectionOnDemand) != 0) ||
 77                 (flags & NetworkReachabilityFlags.ConnectionOnTraffic) != 0
 78                 )
 79             {
 80                 if ((flags & NetworkReachabilityFlags.InterventionRequired) == 0)
 81                 {
 82                     strNetworkType = "WIFI";
 83                 }
 84             }
 85 
 86             if ((flags & NetworkReachabilityFlags.IsWWAN)==NetworkReachabilityFlags.IsWWAN)
 87             {
 88                 if ((float)PlatformName.iOS > 7)
 89                 {
 90                     CoreTelephony.CTTelephonyNetworkInfo info = new CoreTelephony.CTTelephonyNetworkInfo();
 91                     string currentRadioAccessTechnology = info.CurrentRadioAccessTechnology;
 92                     if (!string.IsNullOrEmpty(currentRadioAccessTechnology))
 93                     {
 94                         if (currentRadioAccessTechnology == "CTRadioAccessTechnologyLTE")
 95                         {
 96                             strNetworkType = "4G";
 97                         }
 98                         else if (currentRadioAccessTechnology == "CTRadioAccessTechnologyEdge" ||
 99                             currentRadioAccessTechnology == "CTRadioAccessTechnologyGPRS"
100                             )
101                         {
102                             strNetworkType = "2G";
103                         }
104                         else
105                         {
106                             strNetworkType = "3G";
107                         }
108                     }
109                 }
110                 else
111                 {
112                     if ((flags & NetworkReachabilityFlags.Reachable)== NetworkReachabilityFlags.Reachable)
113                     {
114                         if ((flags & NetworkReachabilityFlags.TransientConnection) == NetworkReachabilityFlags.TransientConnection)
115                         {
116                             if ((flags & NetworkReachabilityFlags.ConnectionRequired) == NetworkReachabilityFlags.ConnectionRequired)
117                             {
118                                 strNetworkType = "2G";
119                             }
120                             else
121                             {
122                                 strNetworkType = "3G";
123                             }
124                         }
125                     }
126                 }
127             }
128 
129             return strNetworkType;
130         }
131 
132         #region 方式一
133         public bool IsConnected { get; set; }
134         public void CheckNetworkConnection()
135         {
136             InternetConnectionStatus();
137         }
138 
139         private void UpdateNetworkStatus()
140         {
141             if (InternetConnectionStatus())
142             {
143                 IsConnected = true;
144             }
145             else if (LocalWifiConnectionStatus())
146             {
147                 IsConnected = true;
148             }
149             else
150             {
151                 IsConnected = false;
152             }
153         }
154 
155         private event EventHandler ReachabilityChanged;
156         private void OnChange(NetworkReachabilityFlags flags)
157         {
158             var h = ReachabilityChanged;
159             if (h != null)
160                 h(null, EventArgs.Empty);
161         }
162 
163         private NetworkReachability defaultRouteReachability;
164         private bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
165         {
166             if (defaultRouteReachability == null)
167             {
168                 defaultRouteReachability = new NetworkReachability(new IPAddress(0));
169                 //defaultRouteReachability.SetCallback(OnChange);
170                 defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
171             }
172             if (!defaultRouteReachability.TryGetFlags(out flags))
173                 return false;
174             return IsReachableWithoutRequiringConnection(flags);
175         }
176 
177         private NetworkReachability adHocWiFiNetworkReachability;
178         private bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags)
179         {
180             if (adHocWiFiNetworkReachability == null)
181             {
182                 adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte[] { 169, 254, 0, 0 }));
183                 //adHocWiFiNetworkReachability.SetCallback(OnChange);
184                 adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
185             }
186 
187             if (!adHocWiFiNetworkReachability.TryGetFlags(out flags))
188                 return false;
189 
190             return IsReachableWithoutRequiringConnection(flags);
191         }
192 
193         public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
194         {
195             // Is it reachable with the current network configuration?
196             bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
197 
198             // Do we need a connection to reach it?
199             bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0;
200 
201             // Since the network stack will automatically try to get the WAN up,
202             // probe that
203             if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
204                 noConnectionRequired = true;
205 
206             return isReachable && noConnectionRequired;
207         }
208 
209         private bool InternetConnectionStatus()
210         {
211             NetworkReachabilityFlags flags;
212             bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
213             if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
214             {
215                 return false;
216             }
217             else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
218             {
219                 return true;
220             }
221             else if (flags == 0)
222             {
223                 return false;
224             }
225 
226             return true;
227         }
228 
229         private bool LocalWifiConnectionStatus()
230         {
231             NetworkReachabilityFlags flags;
232             if (IsAdHocWiFiNetworkAvailable(out flags))
233             {
234                 if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
235                     return true;
236             }
237             return false;
238         }
239 
240 
241 
242         #endregion
243 
244         #region 方式二
245 
246         #endregion
247     }
248 }
IOS
原文地址:https://www.cnblogs.com/zuimengaitianya/p/6165405.html