獲取本機IP
public static string GetLocalIP()
{
string strIP = string.Empty;
try
{
string hostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(hostName);
for (int i = 0; i < ipEntry.AddressList.Length; i++)
{
if (ipEntry.AddressList[i].AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork)
{
strIP= ipEntry.AddressList[i].ToString();
break;
}
}
}
catch (Exception)
{
}
return strIP;
}
檢查IP地址合法性
public static bool CheckIP(string strIP)
{
strIP = strIP.Replace(" ", "");
return Regex.IsMatch(strIP, @"^(([1-9]\d?)|(1\d{2})|(2[01]\d)|(22[0-3]))(\.((1?\d\d?)|(2[04]/d)|(25[0-5]))){3}$");
}
驗證某個IP是否可以Ping通
public static bool TestNetConnectity(string strIP)
{
if (!CheckIP(strIP)) return false;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "test...test...test...test...test...test...";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(strIP, timeout, buffer, options);
return (reply.Status == IPStatus.Success);
}
多次Ping一個IP地址,看是否一直能Ping通
public bool TestNetConnected(string strIP,int waitSeconds,int iTestTimes)
{
bool isConnected = true;
for (int i = 0; i < iTestTimes; i++)
{
if (!TestNetConnectity(strIP)) isConnected = false;
Thread.Sleep(waitSeconds * 1000);
}
return isConnected;
}