本文整理汇总了C#中System.Net.NetworkInformation.Ping.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Ping.Dispose方法的具体用法?C# Ping.Dispose怎么用?C# Ping.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.NetworkInformation.Ping
的用法示例。
在下文中一共展示了Ping.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Available
public static bool Available(string IPorHostname)
{
bool bAvailable = false;
Ping ping = new Ping();
try
{
PingReply pingReply = ping.Send(IPorHostname, timeout);
if (pingReply.Status == IPStatus.Success)
{
bAvailable = true;
}
}
catch (Exception)
{
bAvailable = false;
}
finally
{
if ( ping!=null)
{
ping.Dispose();
ping = null;
}
}
return bAvailable;
}
示例2: Trace
public static void Trace(IPAddress destination, Func<IPAddress, TracertNode, bool> callback)
{
if (destination == null)
{
throw new ArgumentNullException("destination");
}
else
{
if (callback == null)
{
throw new ArgumentNullException("callback");
}
else
{
var syncroot = new object();
var buffer = new byte[INT_BufferSize];
var options = new PingOptions(1, true);
var ping = new Ping();
ping.PingCompleted += (sender, e) =>
{
var address = e.Reply.Address;
var status = e.Reply.Status;
back:
var done = !callback.Invoke(destination, new TracertNode(address, status, e.Reply.Options.Ttl)) || address.Equals(destination);
if (done)
{
try
{
if (ping != null)
{
ping.Dispose();
}
}
finally
{
ping = null;
}
}
else
{
lock (syncroot)
{
if (ping == null)
{
address = destination;
status = IPStatus.Unknown;
goto back;
}
else
{
options.Ttl++;
ping.SendAsync(destination, INT_TimeoutMilliseconds, buffer, options, null);
}
}
}
};
ping.SendAsync(destination, INT_TimeoutMilliseconds, buffer, options, null);
}
}
}
示例3: DoPings
private void DoPings()
{
while (work)
{
Thread.Sleep(250);
while (checkPing)
{
try
{
Ping ping = new Ping();
PingReply reply = ping.Send(host.IPAddress);
if (reply.Status == IPStatus.Success)
{
checkPing = false;
if ((int)host.Status <= (int)DroneStatus.NotConnected)
host.Status = DroneStatus.Available;
}
ping.Dispose();
}
catch
{
/* ignore not pingable
if ((int)host.Status == (int)DroneStatus.NotConnected)
host.Status = DroneStatus.Invalid; */
}
Thread.Sleep(250);
}
}
}
示例4: Check_Internet
public static bool Check_Internet()
{
Ping ping = new Ping();
PingReply reply;
try { reply = ping.Send(ping_web, 1000); }
catch (Exception e) { Console.WriteLine("Exception at ping\n {0}", e.Message); return false; }
ping.Dispose();
ping = null;
Console.WriteLine("Ping to google.es -> {0}", Enum.GetName(typeof(IPStatus), reply.Status));
if (reply.Status != IPStatus.Success)
return false;
else
return true;
}
示例5: ManualPingServer
private void ManualPingServer(object ipAddress)
{
String ip = ipAddress.ToString();
Invoke(new UpdateStatusBarDelegate(UpdateStatusBar), "Pinging " + ip);
//Invoke(new UpdateLogDelegate(UpdateLog), "Pinging " + ip);
Ping p = new Ping();
try
{
PingReply pr = p.Send(ip);
if (pr != null && pr.Status == IPStatus.Success)
{
IPHostEntry hostEntry = Dns.GetHostEntry(ip);
if (hostEntry.HostName != "")
Invoke(new UpdateServerBrowserDelegate(UpdateServerBrowser), new[] { ip, hostEntry.HostName });
else
Invoke(new UpdateServerBrowserDelegate(UpdateServerBrowser), new[] { ip, ip });
}
//Invoke(new UpdateStatusBarDelegate(UpdateStatusBar), "Finished pinging: " + ip);
}
catch (Exception)
{
Invoke(new UpdateLogDelegate(UpdateLog), "Unable to access IP: " + ip);
//Invoke(new UpdateStatusBarDelegate(UpdateStatusBar), "Unsuccessful ping of: " + ip);
Logger.Instance.Log(this.GetType(), LogType.Info, "Unable to access IP: " + ip);
}
finally
{
p.Dispose();
}
}
示例6: Ping
internal static bool Ping(string hostname)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
// Create a buffer of 32 bytes of data to be transmitted.
const string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
//TODO: Move the Ping timeout to the settings file
const int timeout = 10000;
PingReply reply = pingSender.Send(hostname, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
pingSender.Dispose();
return true;
}
reply = pingSender.Send(hostname, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
pingSender.Dispose();
return true;
}
pingSender.Dispose();
return false;
}
示例7: ProcessHop
private void ProcessHop(IPAddress address, IPStatus status, string time)
{
Int64 roundTripTime = 0;
if (status == IPStatus.Success || status == IPStatus.TtlExpired)
{
System.Net.NetworkInformation.Ping ping2 = new System.Net.NetworkInformation.Ping();
try
{
// Do another ping to get the roundtrip time per address.
PingReply reply = ping2.Send(address, this.HopTimeOut);
roundTripTime = reply.RoundtripTime;
status = reply.Status;
}
catch (Exception ex)
{
Log.Info(String.Empty, ex);
}
finally
{
ping2.Dispose();
ping2 = null;
}
}
if (this.cancel)
return;
TraceRouteHopData hop = new TraceRouteHopData(this.counter++, address, roundTripTime, status, time);
try
{
if (status == IPStatus.Success && this.ResolveNames)
{
IPHostEntry entry = Dns.GetHostEntry(address);
hop.HostName = entry.HostName;
}
}
catch (SocketException)
{
// No such host is known error.
hop.HostName = String.Empty;
}
lock (this.hopList)
this.hopList.Add(hop);
if (this.RouteHopFound != null)
this.RouteHopFound(this, new RouteHopFoundEventArgs(hop, this.Idle));
this.Idle = address.Equals(this.destinationIP);
lock (this.hopList)
{
if (!this.Idle && this.hopList.Count >= this.HopLimit - 1)
this.ProcessHop(this.destinationIP, IPStatus.Success, DateTime.Now.ToLongTimeString());
}
if (this.Idle)
{
this.OnCompleted();
this.Dispose();
}
}
示例8: ProcessNode
protected void ProcessNode(IPAddress address, IPStatus status)
{
long roundTripTime = 0;
if (status == IPStatus.TtlExpired || status == IPStatus.Success)
{
var pingIntermediate = new Ping();
try
{
//Compute roundtrip time to the address by pinging it
PingReply reply = pingIntermediate.Send(address, _timeout);
roundTripTime = reply.RoundtripTime;
status = reply.Status;
}
catch (PingException e)
{
//Do nothing
System.Diagnostics.Trace.WriteLine(e);
}
finally
{
pingIntermediate.Dispose();
}
}
var node = new TracertNode(address, roundTripTime, status);
lock (_nodes)
{
_nodes.Add(node);
}
if (RouteNodeFound != null)
RouteNodeFound(this, new RouteNodeFoundEventArgs(node, IsDone));
IsDone = address.Equals(_destination);
lock (_nodes)
{
if (!IsDone && _nodes.Count >= _maxHops - 1)
ProcessNode(_destination, IPStatus.Success);
}
}
示例9: PingIp
private IPStatus PingIp(String ip)
{
Ping p = new Ping();
if (!String.IsNullOrEmpty(ip))
{
try
{
PingReply pr = p.Send(ip);
p.Dispose();
if (pr != null)
return pr.Status;
}
catch (Exception ex)
{
p.Dispose();
ToLog = "Error: " + ex.Message;
}
}
else
p.Dispose();
return IPStatus.Unknown;
}
示例10: PingTimer_Tick
void PingTimer_Tick(object sender, EventArgs e)
{
(new Thread(() =>
{
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
Thread.CurrentThread.IsBackground = true; // cancel this thread when the window is being closed
Ping Ping = new Ping();
try
{
long PingTime = Ping.Send(Server.ServerHost).RoundtripTime;
MainWindow.Dispatcher.BeginInvoke(
(Action)(() =>
{
MainWindow.Label_PingInfo.Content = R.String("Ping") + ": " + PingTime.ToString() + " ms";
}));
}
catch (Exception)
{
MainWindow.Dispatcher.BeginInvoke(
(Action)(() =>
{
MainWindow.Label_PingInfo.Content = R.String("NoNetworkConnection");
}));
}
finally
{
Ping.Dispose();
}
})).Start();
}
示例11: IsConnectedToInternet
private Boolean IsConnectedToInternet()
{
Boolean result = false;
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(host, 1000); //expect a response within 1 second
if (reply.Status == IPStatus.Success)
return true;
}
catch { }
finally
{
ping.Dispose();
}
return result;
}
示例12: PingNetAddress
/// <summary>
/// ping 具体的网址看能否ping通
/// </summary>
/// <param name="strNetAdd"></param>
/// <returns></returns>
private static bool PingNetAddress(string strNetAdd)
{
bool Flage = false;
Ping ping = new Ping();
try
{
PingReply pr = ping.Send(strNetAdd, 3000);
if (pr.Status == IPStatus.TimedOut)
{
Flage = false;
}
if (pr.Status == IPStatus.Success)
{
Flage = true;
}
else
{
Flage = false;
}
}
catch
{
Flage = false;
}
finally
{
ping.Dispose();
}
return Flage;
}
示例13: Ping
/// <summary>
/// ping大屏地址
/// </summary>
/// <param name="timeout">超时毫秒数</param>
/// <returns>ping通返回true,否则返回false</returns>
public bool Ping(int timeout)
{
if (IP == "0.0.0.0") return false;
Ping p = new Ping();
PingReply r = p.Send(IP,timeout);
p.Dispose();
IsConnected = (r.Status == IPStatus.Success);
return (r.Status == IPStatus.Success);
}
示例14: bw_DoWork
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
bool firstrun = true;
DateTime downtimestart = DateTime.Now;
DateTime downtimeend = DateTime.Now;
ConnectionStatus laststatus = ConnectionStatus.Unknown;
int count = 0;
long total = 0;
// Only keep the last 50 pings in the avg
if (count >= 50)
{
total = total / count;
count = 1;
}
while (!worker.CancellationPending)
{
StringBuilder history = new StringBuilder();
StringBuilder log = new StringBuilder();
ProgressData pd = new ProgressData() { History = string.Empty, Log = string.Empty };
Ping pingSender = new Ping();
try
{
IPAddress address = IPAddress.Parse(Properties.Settings.Default.DefaultGatewayIP);
PingReply reply = pingSender.Send(address, 5000);
count++;
total = total + reply.RoundtripTime;
if (reply.Status == IPStatus.Success)
{
if (firstrun)
{
history.AppendLine("Connection Status: Up");
log.AppendLine("Connection Status: Up");
firstrun = false;
}
if (laststatus == ConnectionStatus.Down)
{
downtimeend = DateTime.Now;
var span = downtimeend - downtimestart;
string status = string.Format("Connection Up: {0} Downtime: {1} hours - {2} minutes - {3} seconds", DateTime.Now, span.Hours, span.Minutes, span.Seconds);
log.AppendLine(status);
history.AppendLine(status);
}
laststatus = ConnectionStatus.Up;
if (verbose) { history.AppendLine(string.Format("Time: {0} Address: {1} Status: {2} RoundTrip: {3} ms Average: {4} ms", DateTime.Now, address.ToString(), reply.Status, reply.RoundtripTime, total / count)); }
}
else
{
firstrun = false;
count = 0;
total = 0;
if (laststatus != ConnectionStatus.Down)
{
downtimestart = DateTime.Now;
string status = string.Format("Connection Down: {0}", DateTime.Now);
log.AppendLine(status);
history.AppendLine(status);
}
laststatus = ConnectionStatus.Down;
if (verbose) { history.AppendLine(string.Format("Time: {0} Address: {1} Status: {2} RoundTrip: {3} ms", DateTime.Now, address.ToString(), reply.Status, reply.RoundtripTime)); }
}
}
catch (PingException pe)
{
history.AppendLine(pe.Message);
}
catch (NetworkInformationException net)
{
history.AppendLine(net.Message);
}
catch (Exception ex)
{
history.AppendLine(ex.Message);
}
finally
{
pingSender.Dispose();
}
if (history.Length > 0) { pd.History = history.ToString(); }
if (log.Length > 0) { pd.Log = log.ToString(); }
//.........这里部分代码省略.........
示例15: StartPing
public void StartPing(object argument)
{
if (IsOffline())
return;
IPAddress ip = (IPAddress)argument;
//set options ttl=128 and no fragmentation
PingOptions options = new PingOptions(128, true);
//create a Ping object
Ping ping = new Ping();
//32 empty bytes buffer
byte[] data = new byte[32];
int received = 0;
List<long> responseTimes = new List<long>();
string resp = string.Empty;
//ping 4 times
for (int i = 0; i < 4; i++)
{
PingReply reply = ping.Send(ip, 1000, data, options);
if (reply != null)
{
switch (reply.Status)
{
case IPStatus.Success:
resp = "Reply from " + reply.Address + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms TTL=" + reply.Options.Ttl;
PingEventArgs pe = new PingEventArgs(resp);
Change(this, pe);
received++;
responseTimes.Add(reply.RoundtripTime);
break;
case IPStatus.TimedOut:
pe = new PingEventArgs("Request timed out.");
Change(this, pe);
break;
default:
pe = new PingEventArgs("Ping failed " + reply.Status.ToString());
Change(this, pe);
break;
}
}
else
{
PingEventArgs pe = new PingEventArgs("Ping failed for an unknown reason");
Change(this, pe);
}
reply = null;
}
ping.Dispose();
//statistics calculations
long averageTime = -1;
long minimumTime = 0;
long maximumTime = 0;
for (int i = 0; i < responseTimes.Count; i++)
{
if (i == 0)
{
minimumTime = responseTimes[i];
maximumTime = responseTimes[i];
}
else
{
if (responseTimes[i] > maximumTime)
{
maximumTime = responseTimes[i];
}
if (responseTimes[i] < minimumTime)
{
minimumTime = responseTimes[i];
}
}
averageTime += responseTimes[i];
}
StringBuilder statistics = new StringBuilder();
statistics.AppendLine();
statistics.AppendLine();
statistics.AppendFormat("Ping statistics for {0}:", ip.ToString());
statistics.AppendLine();
statistics.AppendFormat(" Packets: Sent = 4, " +
"Received = {0}, Lost = {1} <{2}% loss>,",
received, 4 - received, Convert.ToInt32(((4 - received) * 100) / 4));
statistics.AppendLine();
statistics.AppendLine();
//show only if loss is not 100%
if (averageTime != -1)
{
statistics.Append("Approximate round trip times in milli-seconds:");
statistics.AppendLine();
//.........这里部分代码省略.........