本文整理汇总了C#中System.Net.NetworkInformation.Ping.Send方法的典型用法代码示例。如果您正苦于以下问题:C# Ping.Send方法的具体用法?C# Ping.Send怎么用?C# Ping.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.NetworkInformation.Ping
的用法示例。
在下文中一共展示了Ping.Send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MyPing
/// <summary>
/// Ping命令检测网络是否畅通
/// </summary>
/// <param name="urls">URL数据</param>
/// <param name="errorCount">ping时连接失败个数</param>
/// <returns></returns>
public static string MyPing(string[] urls, out int errorCount)
{
StringBuilder sb = new StringBuilder();
Ping ping = new Ping();
errorCount = 0;
try
{
PingReply pr;
for (int i = 0; i < urls.Length; i++)
{
pr = ping.Send(urls[i]);
if (pr.Status != IPStatus.Success)
{
sb.AppendLine("error Ping " + urls[i] + " " + pr.Status.ToString());
errorCount++;
}
sb.AppendLine("Ping " + urls[i] + " " + pr.Status.ToString());
}
}
catch (Exception ex)
{
sb.AppendLine("error!! " + ex.Message);
errorCount = urls.Length;
}
//if (errorCount > 0 && errorCount < 3)
// isconn = true;
return sb.ToString();
}
示例2: ReadAndPing
public void ReadAndPing(string path)
{
File.OpenRead(path);
ConsoleKeyInfo btn;
do // Начала цикла
{
string ip = File.ReadLines(path);
while (true) //читаем в ip строки из файла в path
{
//Console.WriteLine(ip);
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.Ttl = 60; //Продолжительность жизни пакета в секундах
int timeout = 120; //Таймаут выводется в ответе reply.RoundtripTime
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //Строка длиной 32 байта
byte[] buffer = Encoding.ASCII.GetBytes(data); //Преобразование строки в байты, выводится reply.Buffer.Length
PingReply reply = pingSender.Send(ip, timeout, buffer, options);
Console.WriteLine("Сервер: {0} Время={1} TTL={2}", reply.Address.ToString(), reply.RoundtripTime, reply.Options.Ttl); //Выводим всё на консоль
//ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли
//if (btn.Key == ConsoleKey.Escape) break;
}
// ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли
// if (btn.Key == ConsoleKey.Escape) break;
btn = Console.ReadKey(); //Переенная для чтения нажатия клавиши
}
while (btn.Key == ConsoleKey.Escape); //Чтение нажатия клавиши.
}
示例3: Ping
public static PingStatus Ping(string deviceName, PingerOptions options)
{
Ping pinger = new Ping();
PingOptions pingOptions = new PingOptions() { DontFragment = options.DontFragment };
// Create a buffer of 32 bytes of data to be transmitted.
byte a = Encoding.ASCII.GetBytes("a")[0];
byte[] buffer = new byte[options.PayloadSize]; // Encoding.ASCII.GetBytes(data);
for (int i = 0; i < options.PayloadSize; i++)
{
buffer[i] = a;
}
try
{
PingReply reply = pinger.Send(deviceName, options.Timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
{
//Ping was successful
return new PingStatus(true, (int)reply.Status, reply.RoundtripTime);
}
//Ping failed
return new PingStatus(false, (int)reply.Status, reply.RoundtripTime);
}
catch (Exception)
{
return new PingStatus(false, 99999, 99999);
}
}
示例4: RemoteEnvironment
public RemoteEnvironment(string ipAddress, string userName, string password, string psExecPath)
{
IpAddress = ipAddress;
UserName = userName;
Password = password;
_psExecPath = psExecPath;
// wait for ping
RetryUtility.RetryAction(() =>
{
var ping = new Ping();
var reply = ping.Send(IpAddress);
OsTestLogger.WriteLine(string.Format("Pinging ip:{0}, reply: {1}", ipAddress, reply.Status));
if (reply.Status != IPStatus.Success)
throw new InvalidOperationException(string.Format("Remote IP {0} ping returns {1}", ipAddress, reply.Status));
}, 50, 5000);
// give time for the RPC service to start
RetryUtility.RetryAction(() => { WmiWrapperInstance = new WmiWrapper(ipAddress, userName, password); }, 10, 5000);
WindowsShellInstance = new WindowsShell(this, psExecPath);
//this will populate the GuestEnvironmentVariables. Short time after start APPDATA may be empty
RetryUtility.RetryAction( InvalidateCachedGuestEnvironmentVariables, 10, 10000);
IsUACEnabled = CheckIsUAC();
}
示例5: PerformPathping
/// <summary>
/// Performs a pathping
/// </summary>
/// <param name="ipaTarget">The target</param>
/// <param name="iHopcount">The maximum hopcount</param>
/// <param name="iTimeout">The timeout for each ping</param>
/// <returns>An array of PingReplys for the whole path</returns>
public static PingReply[] PerformPathping(IPAddress ipaTarget, int iHopcount, int iTimeout)
{
System.Collections.ArrayList arlPingReply = new System.Collections.ArrayList();
Ping myPing = new Ping();
PingReply prResult = null;
int iTimeOutCnt = 0;
for (int iC1 = 1; iC1 < iHopcount && iTimeOutCnt<5; iC1++)
{
prResult = myPing.Send(ipaTarget, iTimeout, new byte[10], new PingOptions(iC1, false));
if (prResult.Status == IPStatus.Success)
{
iC1 = iHopcount;
iTimeOutCnt = 0;
}
else if (prResult.Status == IPStatus.TtlExpired)
{
iTimeOutCnt = 0;
}
else if (prResult.Status == IPStatus.TimedOut)
{
iTimeOutCnt++;
}
arlPingReply.Add(prResult);
}
PingReply[] prReturnValue = new PingReply[arlPingReply.Count];
for (int iC1 = 0; iC1 < arlPingReply.Count; iC1++)
{
prReturnValue[iC1] = (PingReply)arlPingReply[iC1];
}
return prReturnValue;
}
示例6: pingHost
public void pingHost(string hostName, int pingCount)
{
if (pingCount == 0)
{
pingCount = 43200;
}
Console.WriteLine("Host, Response Time, Status, Time ");
String fileName = String.Format(@"tping-{0}-{1}-{2}-{3}.csv", DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
for (int i = 0; i < pingCount; i++)
{
Ping ping = new Ping();
StreamWriter processedData = new StreamWriter(@fileName, true);
try
{
PingReply pingReply = ping.Send(hostName);
processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status);
processedData.Close();
Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status);
}
catch (System.Net.NetworkInformation.PingException)
{
processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error");
Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error");
processedData.Close();
//Console.WriteLine(Ex);
//Environment.Exit(0);
}
Thread.Sleep(2000);
}
Console.WriteLine("\n" + "tping complete - {0} pings logged in {1}", pingCount, fileName);
}
示例7: IsHostAccessible
public static bool IsHostAccessible(string hostNameOrAddress)
{
if (String.IsNullOrEmpty(hostNameOrAddress))
return false;
using (var ping = new Ping())
{
PingReply reply;
try
{
reply = ping.Send(hostNameOrAddress, PingTimeout);
}
catch (Exception ex)
{
if (ex is ArgumentNullException ||
ex is ArgumentOutOfRangeException ||
ex is InvalidOperationException ||
ex is SocketException )
{
return false;
}
throw;
}
if (reply != null) return reply.Status == IPStatus.Success;
}
return false;
}
示例8: ConnectGoogleTW
bool ConnectGoogleTW()
{
//Google網址
string googleTW = "www.google.tw";
//Ping網站
Ping p = new Ping();
//網站的回覆
PingReply reply;
try
{
//取得網站的回覆
reply = p.Send(googleTW);
//如果回覆的狀態為Success則return true
if (reply.Status == IPStatus.Success) { return true; }
}
//catch這裡的Exception, 是有可能網站當下的某某狀況造成, 可以直接讓它傳回false.
//或在重覆try{}裡的動作一次
catch { return false; }
//如果reply.Status !=IPStatus.Success, 直接回傳false
return false;
}
示例9: PingIpOrDomainName
public static bool PingIpOrDomainName(string strIpOrDname) {
try
{
Ping objPingSender = new Ping();
PingOptions objPinOptions = new PingOptions();
objPinOptions.DontFragment = true;
string data = "";
byte[] buffer = Encoding.UTF8.GetBytes(data);
int intTimeout = 120;
PingReply objRPinReply = objPingSender.Send(strIpOrDname, intTimeout, buffer, objPinOptions);
string strInfo = objRPinReply.Status.ToString();
if (strInfo == "Success")
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
示例10: Ping
private bool Ping()
{
Ping pingSender = new Ping();
if (string.IsNullOrEmpty(_hostAddress))
{
try
{
IPInfo ipInfo = IPInfo.CreateFromMac(_macAddress);
_hostAddress = ipInfo.IPAddress;
}
catch (Exception ex)
{
_logger.Warn(ex.Message);
return false;
}
}
PingReply reply = pingSender.Send(_hostAddress);
IPStatus status = reply.Status;
if (reply.Status == IPStatus.Success)
{
return true;
}
return false;
}
示例11: CheckForNewVersion
/// <summary>
/// Checks available version.
/// </summary>
public static string CheckForNewVersion()
{
try
{
Ping ping = new Ping();
PingReply reply = ping.Send(PING_TEST_WEB_SITE);
if (reply.Status == IPStatus.Success)
{
string httpQuery = PING_WEBSERVICE + "?v=" + TechnicalSettings.SoftwareVersion;
WebRequest web = System.Net.HttpWebRequest.Create(httpQuery);
WebResponse response = web.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string xml = sr.ReadToEnd();
response.Close();
if (xml.Contains(VERSION))
{
int a = xml.IndexOf(VERSION);
int b = xml.IndexOf("</version>");
string version = xml.Substring(a + VERSION.Length, b - a - VERSION.Length);
if (TechnicalSettings.IsThisVersionNewer(version))
{
return version;
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine("AppMain.PingWeb failed. \n" + ex.Message);
}
return null;
}
示例12: PingHost
public void PingHost(Host host, int numeroTestes)
{
bool pingou = true;
Ping pinger = new Ping();
try
{
for (int i = 0; i < numeroTestes; i++)
{
if (!pingou)
break;
PingReply reply = pinger.Send(host.ip);
pingou = reply.Status == IPStatus.Success;
}
}
catch (PingException)
{
pingou = false;
}
if (host.em_pe != pingou)
{
host.em_pe = pingou;
host.ultima_alteracao = DateTime.Now.ToString();
banco.atualizarHost(host);
}
}
示例13: Connect
public static void Connect()
{
try
{
var ping = new Ping();
var reply = ping.Send(IpAdress, 10);
Logger.Info("Attempting to connect to server.");
if (reply.Status == IPStatus.Success)
{
MainTcpClient = new TcpClient(IPAddress.Parse(IpAdress).ToString(), Port);
Logger.Info($"{((IPEndPoint)MainTcpClient.Client.RemoteEndPoint).Address}" +
": Connected to server.");
MainStream = MainTcpClient.GetStream();
}
else
{
Logger.Info("Failed to connect to server.");
throw new PingException("Servern är inte aktiv");
}
}
catch (PingException pingException)
{
Console.WriteLine("PingException: " + pingException.Message);
}
catch (SocketException socketException)
{
Console.WriteLine("SocketException:" + socketException.Message);
}
}
示例14: Ping
public PingReply Ping(string hostOrIp)
{
Ping pingSender = new Ping();
//Ping 选项设置
PingOptions options = new PingOptions();
options.DontFragment = true;
//测试数据
string data = "test data abcabc";
byte[] buffer = Encoding.ASCII.GetBytes(data);
//设置超时时间
int timeout = 1200;
//调用同步 send 方法发送数据,将返回结果保存至PingReply实例
var reply = pingSender.Send(hostOrIp, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
return reply;
/*lst_PingResult.Items.Add("答复的主机地址:" + reply.Address.ToString());
lst_PingResult.Items.Add("往返时间:" + reply.RoundtripTime);
lst_PingResult.Items.Add("生存时间(TTL):" + reply.Options.Ttl);
lst_PingResult.Items.Add("是否控制数据包的分段:" + reply.Options.DontFragment);
lst_PingResult.Items.Add("缓冲区大小:" + reply.Buffer.Length); */
}
else
throw new ApplicationException("Can't find the arrive at target " + hostOrIp.ToString());
}
示例15: StartConnect
public bool StartConnect(string IP, int TcpPort, int CtrlPort)
{
var ping = new Ping();
if (ping.Send(IP).Status != IPStatus.Success)
{
Console.Write("サーバーがPINGに応答しません。接続しますか?\n10秒でキャンセルされます。(y/n):");
string Res = new Reader().ReadLine(10000);
if (Res == null || !Res.ToLower().StartsWith("y"))
return false;
}
CommonManager.Instance.NWMode = true;
if (!CommonManager.Instance.NW.ConnectServer(IP, (uint)CtrlPort
, (uint)TcpPort, OutsideCmdCallback, this)) return false;
byte[] binData;
if (CommonManager.Instance.CtrlCmd.SendFileCopy("ChSet5.txt", out binData) == 1)
{
string filePath = @".\Setting";
Directory.CreateDirectory(filePath);
filePath += @"\ChSet5.txt";
using (BinaryWriter w = new BinaryWriter(File.Create(filePath)))
{
w.Write(binData);
w.Close();
}
ChSet5.LoadFile();
return true;
}
return false;
}