/// <summary> /// https://edi.wang/post/2017/11/6/use-icmp-ping-in-netcore-20 /// </summary> /// <param name="target"></param> /// <returns></returns> public async Task <NetworkReply> ExecuteICMP(string target) { using (Ping pingSender = new Ping()) { // Create a buffer of 32 bytes of data to be transmitted. string data = ""; byte[] buffer = Encoding.ASCII.GetBytes(data); // Wait 12 seconds for a reply. int timeout = 12000; PingOptions options = new PingOptions(64, true); NetworkReply network = new NetworkReply(); PingReply reply = await pingSender.SendPingAsync(target, timeout, buffer, options); var address = reply.Address; network.AddressFamily = address != null?address.AddressFamily.ToString() : string.Empty; network.IP = address != null?address.ToString() : string.Empty; network.IsIPv4MappedToIPv6 = address != null ? address.IsIPv4MappedToIPv6 : false; network.IsIPv6Multicast = address != null ? address.IsIPv6Multicast : false; network.IsIPv6LinkLocal = address != null ? address.IsIPv6LinkLocal : false; network.IsIPv6SiteLocal = address != null ? address.IsIPv6SiteLocal : false; network.IsIPv6Teredo = address != null ? address.IsIPv6SiteLocal : false; network.TargetHost = target; network.Status = reply.Status == IPStatus.Success; return(network); } }
public void Test_NetworkService_ExecuteICMP() { // Using google information string targetHost = "google.com"; string family = "InterNetwork"; PingReplyService service = new PingReplyService(this.MockAppSettings.Object); NetworkReply result = Task.Run(async() => { return(await service.ExecuteICMP(targetHost)); }) .GetAwaiter() .GetResult(); Assert.IsFalse(result.IsIPv4MappedToIPv6); Assert.IsFalse(result.IsIPv6LinkLocal); Assert.IsFalse(result.IsIPv6Multicast); Assert.IsFalse(result.IsIPv6SiteLocal); Assert.IsFalse(result.IsIPv6Teredo); Assert.AreEqual(result.AddressFamily.ToString(), family); Assert.IsTrue(result.Status); this.VerifyAndTearDown(); }
public async Task <NetworkReply> Icmp(string target) { NetworkReply reply = new NetworkReply(); try { reply = await this._pingReplyService.ExecuteICMP(target); } catch (PingException pex) { reply.Message = pex.Message; reply.StackTrace = pex.StackTrace; } catch (Exception ex) { reply.Message = ex.InnerException.Message; reply.StackTrace = ex.InnerException.StackTrace; } return(reply); }