private void ContinueAsyncSend(object state) { // // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission // and the operation, and to be sure that IPAddress.ToString() is called and not some override that // always returns "localhost" or something. // Debug.Assert(asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress addressSnapshot = Dns.GetHostAddresses(stateObject.hostName)[0]; (new NetworkInformationPermission(NetworkInformationAccess.Ping)).Demand(); InternalSend(addressSnapshot, stateObject.buffer, stateObject.timeout, stateObject.options, true); } catch (Exception e) { PingException pe = new PingException(SR.GetString(SR.net_ping), e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); Finish(true); asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); } }
// Private callback invoked when icmpsendecho APIs succeed. private void PingCallback() { TaskCompletionSource <PingReply> tcs = _taskCompletionSource; _taskCompletionSource = null; PingReply reply = null; Exception error = null; bool canceled = false; try { lock (_lockObject) { canceled = _canceled; // Parse reply buffer. SafeLocalAllocHandle buffer = _replyBuffer; // Marshals and constructs new reply. if (_ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure <Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure <Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmpEchoReply(icmpReply); } } } catch (Exception e) { // In case of failure, create a failed event arg. error = new PingException(SR.net_ping, e); } finally { FreeUnmanagedStructures(); UnregisterWaitHandle(); Finish(); } // Once we've called Finish, complete the task if (canceled) { tcs.SetCanceled(); } else if (reply != null) { tcs.SetResult(reply); } else { Debug.Assert(error != null); tcs.SetException(error); } }
// Private callback invoked when icmpsendecho APIs succeed. private static void PingCallback(object state, bool signaled) { Ping ping = (Ping)state; PingCompletedEventArgs eventArgs = null; bool cancelled = false; AsyncOperation asyncOp = null; SendOrPostCallback onPingCompletedDelegate = null; try { lock (ping._lockObject) { cancelled = ping._cancelled; asyncOp = ping._asyncOp; onPingCompletedDelegate = ping._onPingCompletedDelegate; if (!cancelled) { // Parse reply buffer. SafeLocalAllocHandle buffer = ping._replyBuffer; // Marshals and constructs new reply. PingReply reply; if (ping._ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure <Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = new PingReply(icmp6Reply, buffer.DangerousGetHandle(), ping._sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure <Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = new PingReply(icmpReply); } eventArgs = new PingCompletedEventArgs(reply, null, false, asyncOp.UserSuppliedState); } else { // Canceled. eventArgs = new PingCompletedEventArgs(null, null, true, asyncOp.UserSuppliedState); } } } catch (Exception e) { // In case of failure, create a failed event arg. PingException pe = new PingException(SR.net_ping, e); eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); } finally { ping.FreeUnmanagedStructures(); ping.UnregisterWaitHandle(); ping.Finish(true); } asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); }
//private callback invoked when icmpsendecho apis succeed private static void PingCallback(object state, bool signaled) { Ping ping = (Ping)state; PingCompletedEventArgs eventArgs = null; bool cancelled = false; AsyncOperation asyncOp = null; SendOrPostCallback onPingCompletedDelegate = null; try { lock (ping.lockObject) { cancelled = ping.cancelled; asyncOp = ping.asyncOp; onPingCompletedDelegate = ping.onPingCompletedDelegate; if (!cancelled) { //parse reply buffer SafeLocalFree buffer = ping.replyBuffer; //marshals and constructs new reply PingReply reply; if (ping.ipv6) { Icmp6EchoReply icmp6Reply = (Icmp6EchoReply)Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(Icmp6EchoReply)); reply = new PingReply(icmp6Reply, buffer.DangerousGetHandle(), ping.sendSize); } else { IcmpEchoReply icmpReply = (IcmpEchoReply)Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(IcmpEchoReply)); reply = new PingReply(icmpReply); } eventArgs = new PingCompletedEventArgs(reply, null, false, asyncOp.UserSuppliedState); } else //cancelled { eventArgs = new PingCompletedEventArgs(null, null, true, asyncOp.UserSuppliedState); } } } // in case of failure, create a failed event arg catch (Exception e) { PingException pe = new PingException(SR.GetString(SR.net_ping), e); eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); } finally { ping.FreeUnmanagedStructures(); ping.UnregisterWaitHandle(); ping.Finish(true); } asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); }
private static void PingCallback(object state, bool signaled) { Ping ping = (Ping)state; PingCompletedEventArgs arg = null; bool cancelled = false; AsyncOperation asyncOp = null; SendOrPostCallback d = null; try { lock (ping.lockObject) { cancelled = ping.cancelled; asyncOp = ping.asyncOp; d = ping.onPingCompletedDelegate; if (!cancelled) { PingReply reply; SafeLocalFree replyBuffer = ping.replyBuffer; if (!ping.ipv6 && !ComNetOS.IsVista) { UnsafeNetInfoNativeMethods.IcmpParseReplies(replyBuffer.DangerousGetHandle(), 0x100ff); } if (ping.ipv6) { Icmp6EchoReply reply2 = (Icmp6EchoReply)Marshal.PtrToStructure(replyBuffer.DangerousGetHandle(), typeof(Icmp6EchoReply)); reply = new PingReply(reply2, replyBuffer.DangerousGetHandle(), ping.sendSize); } else { IcmpEchoReply reply3 = (IcmpEchoReply)Marshal.PtrToStructure(replyBuffer.DangerousGetHandle(), typeof(IcmpEchoReply)); reply = new PingReply(reply3); } arg = new PingCompletedEventArgs(reply, null, false, asyncOp.UserSuppliedState); } else { arg = new PingCompletedEventArgs(null, null, true, asyncOp.UserSuppliedState); } } } catch (Exception exception) { PingException error = new PingException(SR.GetString("net_ping"), exception); arg = new PingCompletedEventArgs(null, error, false, asyncOp.UserSuppliedState); } finally { ping.FreeUnmanagedStructures(); ping.UnregisterWaitHandle(); ping.Finish(true); } asyncOp.PostOperationCompleted(d, arg); }
private static bool handlePingException(System.Net.NetworkInformation.PingException ex, MethodBase Method) { switch (ex.HResult) { case -2146233079: return(false); default: UnHandledError(ex, ex.HResult, Method); return(false); } }
private void InternalSendAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options) { AsyncOperation asyncOp = _asyncOp; SendOrPostCallback callback = _onPingCompletedDelegate; // TODO: Implement this (#2487) PingException pe = new PingException(SR.net_ping, new PlatformNotSupportedException()); var ea = new PingCompletedEventArgs( new PingReply(address, default(PingOptions), default(IPStatus), default(long), buffer), pe, false, asyncOp.UserSuppliedState); Finish(); asyncOp.PostOperationCompleted(callback, ea); }
private void ContinueAsyncSend(object state) { AsyncStateObject obj2 = (AsyncStateObject)state; try { IPAddress address = Dns.GetHostAddresses(obj2.hostName)[0]; new NetworkInformationPermission(NetworkInformationAccess.Ping).Demand(); this.InternalSend(address, obj2.buffer, obj2.timeout, obj2.options, true); } catch (Exception exception) { PingException error = new PingException(SR.GetString("net_ping"), exception); PingCompletedEventArgs arg = new PingCompletedEventArgs(null, error, false, this.asyncOp.UserSuppliedState); this.Finish(true); this.asyncOp.PostOperationCompleted(this.onPingCompletedDelegate, arg); } }
private void ContinueAsyncSend(object state) { Debug.Assert(_asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress address = Dns.GetHostAddressesAsync(stateObject.HostName).GetAwaiter().GetResult()[0]; InternalSendAsync(address, stateObject.Buffer, stateObject.Timeout, stateObject.Options); } catch (Exception e) { PingException pe = new PingException(SR.net_ping, e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, _asyncOp.UserSuppliedState); Finish(); _asyncOp.PostOperationCompleted(_onPingCompletedDelegate, eventArgs); } }
// Private callback invoked when icmpsendecho APIs succeed. private void PingCallback() { TaskCompletionSource <PingReply> tcs = _taskCompletionSource; _taskCompletionSource = null; PingReply reply = null; Exception error = null; bool canceled = false; try { lock (_lockObject) { canceled = _canceled; reply = CreatePingReply(); } } catch (Exception e) { // In case of failure, create a failed event arg. error = new PingException(SR.net_ping, e); } finally { Cleanup(isAsync: true, isComplete: true); } // Once we've called Finish, complete the task if (canceled) { tcs.SetCanceled(); } else if (reply != null) { tcs.SetResult(reply); } else { Debug.Assert(error != null); tcs.SetException(error); } }
private void ContinueAsyncSend(object state) { // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission // check and the operation, and to be sure that IPAddress.ToString() is called and not some override. Debug.Assert(_asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress addressSnapshot = Dns.GetHostAddressesAsync(stateObject.HostName).GetAwaiter().GetResult()[0]; InternalSend(addressSnapshot, stateObject.Buffer, stateObject.Timeout, stateObject.Options, true); } catch (Exception e) { PingException pe = new PingException(SR.net_ping, e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, _asyncOp.UserSuppliedState); Finish(true); _asyncOp.PostOperationCompleted(_onPingCompletedDelegate, eventArgs); } }
public void SendAll() { var ping = new Net.Ping(); var replies = new Net.PingReply[interfaces.Count]; var errors = new Net.PingException[interfaces.Count]; for (var i = 0; i < interfaces.Count; i++) { var ip = interfaces[i]; try { replies[i] = ping.Send(ip.Address); } catch (Net.PingException e) { errors[i] = e; } } UpdateConsole(replies); }
private void ProcessPingStatus(ManagementBaseObject pingStatus) { string str = (string)LanguagePrimitives.ConvertTo(pingStatus.GetPropertyValue("Address"), typeof(string), CultureInfo.InvariantCulture); int num = (int)LanguagePrimitives.ConvertTo(pingStatus.GetPropertyValue("PrimaryAddressResolutionStatus"), typeof(int), CultureInfo.InvariantCulture); if (num == 0) { int num1 = (int)LanguagePrimitives.ConvertTo(pingStatus.GetPropertyValue("StatusCode"), typeof(int), CultureInfo.InvariantCulture); if (num1 == 0) { this.quietResults[str] = true; if (!this.quiet) { base.WriteObject(pingStatus); } } else { if (!this.quiet) { Win32Exception win32Exception = new Win32Exception(num1); string str1 = StringUtil.Format(ComputerResources.NoPingResult, str, win32Exception.Message); Exception pingException = new PingException(str1, win32Exception); ErrorRecord errorRecord = new ErrorRecord(pingException, "TestConnectionException", ErrorCategory.ResourceUnavailable, str); base.WriteError(errorRecord); return; } } } else { if (!this.quiet) { Win32Exception win32Exception1 = new Win32Exception(num); string str2 = StringUtil.Format(ComputerResources.NoPingResult, str, win32Exception1.Message); Exception exception = new PingException(str2, win32Exception1); ErrorRecord errorRecord1 = new ErrorRecord(exception, "TestConnectionException", ErrorCategory.ResourceUnavailable, str); base.WriteError(errorRecord1); return; } } }
private bool InitProcessPing(String targetNameOrAddress, out String resolvedTargetName, out IPAddress targetAddress) { IPHostEntry hostEntry = null; resolvedTargetName = targetNameOrAddress; if (IPAddress.TryParse(targetNameOrAddress, out targetAddress)) { if (ResolveDestination) { hostEntry = Dns.GetHostEntry(targetNameOrAddress); resolvedTargetName = hostEntry.HostName; } } else { try { hostEntry = Dns.GetHostEntry(targetNameOrAddress); if (ResolveDestination) { resolvedTargetName = hostEntry.HostName; hostEntry = Dns.GetHostEntry(hostEntry.HostName); } } catch (Exception ex) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, TestConnectionResources.CannotResolveTargetName); Exception pingException = new System.Net.NetworkInformation.PingException(message, ex); ErrorRecord errorRecord = new ErrorRecord(pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, resolvedTargetName); WriteError(errorRecord); return(false); } if (IPv6 || IPv4) { AddressFamily addressFamily = IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; foreach (var address in hostEntry.AddressList) { if (address.AddressFamily == addressFamily) { targetAddress = address; break; } } if (targetAddress == null) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, TestConnectionResources.TargetAddressAbsent); Exception pingException = new System.Net.NetworkInformation.PingException(message, null); ErrorRecord errorRecord = new ErrorRecord(pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, resolvedTargetName); WriteError(errorRecord); return(false); } } else { targetAddress = hostEntry.AddressList[0]; } } return(true); }
private void ProcessPing(String targetNameOrAddress) { String resolvedTargetName = null; IPAddress targetAddress = null; if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress)) { return; } if (!Continues.IsPresent) { WritePingHeader(resolvedTargetName, targetAddress.ToString()); } bool quietResult = true; byte[] buffer = GetSendBuffer(BufferSize); Ping sender = new Ping(); PingOptions pingOptions = new PingOptions(MaxHops, DontFragment.IsPresent); PingReply reply = null; PingReport pingReport = new PingReport(Source, resolvedTargetName); int timeout = TimeoutSeconds * 1000; int delay = Delay * 1000; for (int i = 1; i <= Count; i++) { try { reply = sender.Send(targetAddress, timeout, buffer, pingOptions); } catch (PingException ex) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message); Exception pingException = new System.Net.NetworkInformation.PingException(message, ex.InnerException); ErrorRecord errorRecord = new ErrorRecord(pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, resolvedTargetName); WriteError(errorRecord); quietResult = false; continue; } if (Continues.IsPresent) { WriteObject(reply); } else { if (Quiet.IsPresent) { // Return 'true' only if all pings have completed successfully. quietResult &= reply.Status == IPStatus.Success; } else { pingReport.Replies.Add(reply); } WritePingProgress(reply); } // Delay between ping but not after last ping. if (i < Count && Delay > 0) { Thread.Sleep(delay); } } if (!Continues.IsPresent) { WritePingFooter(); } if (Quiet.IsPresent) { WriteObject(quietResult); } else { WriteObject(pingReport); } }
private void ProcessMTUSize(String targetNameOrAddress) { PingReply reply, replyResult = null; String resolvedTargetName = null; IPAddress targetAddress = null; if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress)) { return; } WriteMTUSizeHeader(resolvedTargetName, targetAddress.ToString()); // Cautious! Algorithm is sensitive to changing boundary values. int HighMTUSize = 10000; int CurrentMTUSize = 1473; int LowMTUSize = targetAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 1280 : 68; int timeout = TimeoutSeconds * 1000; try { Ping sender = new Ping(); PingOptions pingOptions = new PingOptions(MaxHops, true); int retry = 1; while (LowMTUSize < (HighMTUSize - 1)) { byte[] buffer = GetSendBuffer(CurrentMTUSize); WriteMTUSizeProgress(CurrentMTUSize, retry); WriteDebug(StringUtil.Format("LowMTUSize: {0}, CurrentMTUSize: {1}, HighMTUSize: {2}", LowMTUSize, CurrentMTUSize, HighMTUSize)); reply = sender.Send(targetAddress, timeout, buffer, pingOptions); // Cautious! Algorithm is sensitive to changing boundary values. if (reply.Status == IPStatus.PacketTooBig) { HighMTUSize = CurrentMTUSize; retry = 1; } else if (reply.Status == IPStatus.Success) { LowMTUSize = CurrentMTUSize; replyResult = reply; retry = 1; } else { // Target host don't reply - try again up to 'Count'. if (retry >= Count) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, reply.Status.ToString()); Exception pingException = new System.Net.NetworkInformation.PingException(message); ErrorRecord errorRecord = new ErrorRecord(pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, targetAddress); WriteError(errorRecord); return; } else { retry++; continue; } } CurrentMTUSize = (LowMTUSize + HighMTUSize) / 2; // Prevent DoS attack. Thread.Sleep(100); } } catch (PingException ex) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, ex.Message); Exception pingException = new System.Net.NetworkInformation.PingException(message, ex.InnerException); ErrorRecord errorRecord = new ErrorRecord(pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, targetAddress); WriteError(errorRecord); return; } WriteMTUSizeFooter(); if (Quiet.IsPresent) { WriteObject(CurrentMTUSize); } else { var res = PSObject.AsPSObject(replyResult); PSMemberInfo sourceProperty = new PSNoteProperty("Source", Source); res.Members.Add(sourceProperty); PSMemberInfo destinationProperty = new PSNoteProperty("Destination", targetNameOrAddress); res.Members.Add(destinationProperty); PSMemberInfo mtuSizeProperty = new PSNoteProperty("MTUSize", CurrentMTUSize); res.Members.Add(mtuSizeProperty); res.TypeNames.Insert(0, "PingReply#MTUSize"); WriteObject(res); } }
private void ProcessTraceroute(String targetNameOrAddress) { String resolvedTargetName = null; IPAddress targetAddress = null; byte[] buffer = GetSendBuffer(BufferSize); if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress)) { return; } WriteConsoleTraceRouteHeader(resolvedTargetName, targetAddress.ToString()); TraceRouteResult traceRouteResult = new TraceRouteResult(Source, targetAddress, resolvedTargetName); int currentHop = 1; Ping sender = new Ping(); PingOptions pingOptions = new PingOptions(currentHop, DontFragment.IsPresent); PingReply reply = null; int timeout = TimeoutSeconds * 1000; do { TraceRouteReply traceRouteReply = new TraceRouteReply(); pingOptions.Ttl = traceRouteReply.Hop = currentHop; currentHop++; // In the specific case we don't use 'Count' property. // If we change 'DefaultTraceRoutePingCount' we should change 'ConsoleTraceRouteReply' resource string. for (int i = 1; i <= DefaultTraceRoutePingCount; i++) { try { reply = sender.Send(targetAddress, timeout, buffer, pingOptions); traceRouteReply.PingReplies.Add(reply); } catch (PingException ex) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message); Exception pingException = new System.Net.NetworkInformation.PingException(message, ex.InnerException); ErrorRecord errorRecord = new ErrorRecord(pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, resolvedTargetName); WriteError(errorRecord); continue; } catch { // Ignore host resolve exceptions. } // We use short delay because it is impossible DoS with trace route. Thread.Sleep(200); } if (ResolveDestination && reply.Status == IPStatus.Success) { traceRouteReply.ReplyRouterName = Dns.GetHostEntry(reply.Address).HostName; } traceRouteReply.ReplyRouterAddress = reply.Address; WriteTraceRouteProgress(traceRouteReply); traceRouteResult.Replies.Add(traceRouteReply); } while (reply != null && currentHop <= sMaxHops && (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut)); WriteTraceRouteFooter(); if (Quiet.IsPresent) { WriteObject(currentHop <= sMaxHops); } else { WriteObject(traceRouteResult); } }
//private callback invoked when icmpsendecho apis succeed private static void PingCallback (object state, bool signaled) { Ping ping = (Ping)state; PingCompletedEventArgs eventArgs = null; bool cancelled = false; AsyncOperation asyncOp = null; SendOrPostCallback onPingCompletedDelegate = null; try { lock (ping.lockObject) { cancelled = ping.cancelled; asyncOp = ping.asyncOp; onPingCompletedDelegate = ping.onPingCompletedDelegate; if (!cancelled) { //parse reply buffer SafeLocalFree buffer = ping.replyBuffer; //marshals and constructs new reply PingReply reply; if (ping.ipv6) { Icmp6EchoReply icmp6Reply = (Icmp6EchoReply)Marshal.PtrToStructure (buffer.DangerousGetHandle (), typeof(Icmp6EchoReply)); reply = new PingReply (icmp6Reply,buffer.DangerousGetHandle(),ping.sendSize); } else { IcmpEchoReply icmpReply = (IcmpEchoReply)Marshal.PtrToStructure (buffer.DangerousGetHandle (), typeof(IcmpEchoReply)); reply = new PingReply (icmpReply); } eventArgs = new PingCompletedEventArgs (reply, null, false, asyncOp.UserSuppliedState); } else { //cancelled eventArgs = new PingCompletedEventArgs (null, null, true, asyncOp.UserSuppliedState); } } } // in case of failure, create a failed event arg catch (Exception e) { PingException pe = new PingException(SR.GetString(SR.net_ping), e); eventArgs = new PingCompletedEventArgs (null,pe, false, asyncOp.UserSuppliedState); } finally { ping.FreeUnmanagedStructures (); ping.UnregisterWaitHandle(); ping.Finish(true); } asyncOp.PostOperationCompleted (onPingCompletedDelegate, eventArgs); }
// Private callback invoked when icmpsendecho APIs succeed. private void PingCallback() { TaskCompletionSource<PingReply> tcs = _taskCompletionSource; _taskCompletionSource = null; PingReply reply = null; Exception error = null; try { lock (_lockObject) { // Parse reply buffer. SafeLocalAllocHandle buffer = _replyBuffer; // Marshals and constructs new reply. if (_ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure<Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure<Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmpEchoReply(icmpReply); } } } catch (Exception e) { // In case of failure, create a failed event arg. error = new PingException(SR.net_ping, e); } finally { FreeUnmanagedStructures(); UnregisterWaitHandle(); Finish(); } // Once we've called Finish, complete the task if (reply != null) { tcs.SetResult(reply); } else { Debug.Assert(error != null); tcs.SetException(error); } }
private void ContinueAsyncSend(object state) { // // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission // and the operation, and to be sure that IPAddress.ToString() is called and not some override that // always returns "localhost" or something. // Debug.Assert(asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject) state; try { IPAddress addressSnapshot = Dns.GetHostAddresses(stateObject.hostName)[0]; (new NetworkInformationPermission(NetworkInformationAccess.Ping)).Demand(); InternalSend (addressSnapshot, stateObject.buffer, stateObject.timeout, stateObject.options, true); } catch(Exception e){ PingException pe = new PingException(SR.GetString(SR.net_ping), e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs (null, pe, false, asyncOp.UserSuppliedState); Finish(true); asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); } }
// Private callback invoked when icmpsendecho APIs succeed. private static void PingCallback(object state, bool signaled) { Ping ping = (Ping)state; PingCompletedEventArgs eventArgs = null; bool cancelled = false; AsyncOperation asyncOp = null; SendOrPostCallback onPingCompletedDelegate = null; try { lock (ping._lockObject) { cancelled = ping._cancelled; asyncOp = ping._asyncOp; onPingCompletedDelegate = ping._onPingCompletedDelegate; if (!cancelled) { // Parse reply buffer. SafeLocalAllocHandle buffer = ping._replyBuffer; // Marshals and constructs new reply. PingReply reply; if (ping._ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure<Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = new PingReply(icmp6Reply, buffer.DangerousGetHandle(), ping._sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure<Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = new PingReply(icmpReply); } eventArgs = new PingCompletedEventArgs(reply, null, false, asyncOp.UserSuppliedState); } else { // Canceled. eventArgs = new PingCompletedEventArgs(null, null, true, asyncOp.UserSuppliedState); } } } catch (Exception e) { // In case of failure, create a failed event arg. PingException pe = new PingException(SR.net_ping, e); eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); } finally { ping.FreeUnmanagedStructures(); ping.UnregisterWaitHandle(); ping.Finish(true); } asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); }