Usare la classe Ping di C# nel modo corretto (.Net 2.0+)…
Casomai servisse a qualcuno, ecco un piccolo esempio di codice che usa la classe Ping di .Net 2.0+ ed evita il bug che genera il “celebre” memory leak che in breve porta all’esaurimento della memoria.
Il codice deriva dall’esempio dell’MSDN ma include il workaround descritto qui.
Nota: ho riscontrato il bug nell’ormai vetusta versione 2.0 del framework .Net ma c’è chi dice che il memory leak ci sia ancora nella 3.5 SP1 ma non ci giurerei…(se preferite un esempio in un C# più “moderno”, date un’occhiata a questo post su StackOverflow).
Ciau! ^^
/**
* FILE : Pinger.cs
* AUTHOR : Gian Paolo "JP" Ghilardi (http://rejex.wordpress.com)
* LICENSE : released under the terms of GPL v2.0 ("only")
* PURPOSE : simple C# example using the .Net Ping class to check
* for the presence of a remote host.
* NOTES : code based on [1]; avoids the memory leak due to the Dispose() usage [2]
*
* EXAMPLE : Pinger.Pinger p = new Pinger.Pinger();
* MessageBox.Show("Reachable? " + p.IsReachable("127.0.0.1"));
*
* TESTED ON :
* - Windows XP, x86 32-bit, VS2005 (.Net 2.0) and SharpDevelop 3.1 (.Net 3.5 SP1)
*
* REFERENCES:
* [1]: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx
* [2]: http://blog.mbcharbonneau.com/2006/11/14/using-the-ping-class-in-net-20-without-memory-leaks/
*/
namespace Pinger
{
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
public class Pinger
{
public bool IsReachable(string TargetIP)
{
Ping pingSender = new Ping(); // [1]
PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply;
try
{
reply = pingSender.Send(TargetIP, timeout, buffer, options);
((IDisposable)pingSender).Dispose(); // Workaround for Ping class "bug" [2]
pingSender = null;
}
catch (Exception)
{
return false;
}
return (reply.Status == IPStatus.Success);
}
}
}
Categories: C Sharp, LinkedIn, Programmazione
C, C Sharp, LinkedIn, Memory leak, ping, Programmazione

Commenti Recenti