You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

//ping通ip类 测试ip地址是否连通
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
namespace RS.DBUtility
{
public class PingHelper
{
/// <summary>
/// 测试ping通
/// </summary>
/// <param name="ip"></param>ip地址
/// <param name="num"></param>ping次数
/// <returns></returns>
public static bool PingFun(string ip, Int32 num = 4)
{
for (int i = 0; i < num; i++) //ping4次 连续ping不通就不通了
{
if (PingConnect(ip))
return true;
}
return false;
}
public static bool PingConnect(string ip)
{
try
{
if (ip == "") return false;
if (ip == "127.0.0.1" || ip == "localhost") return true;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "pingip";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 200;
//如果网络连接成功PING就应该有返回否则网络连接有问题
PingReply reply = pingSender.Send(ip, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
return true;
}
else return false;
}
catch
{
return false;
}
}
public static bool PingConnectString(string constr)
{
try
{
SqlConnectionStringBuilder con = new SqlConnectionStringBuilder(constr);
string ip = con.DataSource;
if (ip == "") return false;
if (ip == "127.0.0.1" || ip.ToLower() == "localhost") return true;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "pingip";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 200;
//测试网络连接目标计算机为192.168.1.1(可以换成你所需要的目标地址)
//如果网络连接成功PING就应该有返回否则网络连接有问题
PingReply reply = pingSender.Send(ip, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
return true;
}
else return false;
}
catch
{
return false;
}
}
}
}