小Lee閑暇時間鑽牛角尖,寫了一個不操作IP字串的遍曆IP段並返回活動IP列表的方法,閑話就不說了,直接貼CODE
IPhost 類
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Diagnostics;
namespace Test2._0
{
class IPhost
{
public IPhost()
{
}
/// <summary>
/// 擷取IP段中的活動IP列表
/// </summary>
/// <param name="startIP">開始IP</param>
/// <param name="endIP">結束IP</param>
/// <returns></returns>
public List<IPAddress> GetLiveIP(IPAddress startIP, IPAddress endIP)
{
List<IPAddress> ipList = new List<IPAddress>();
IPAddress currentIP = new IPAddress(startIP.Address);
currentIP = startIP;
while (currentIP.Address <= endIP.Address)
{
if (getIpState(currentIP) == "串連")
{
ipList.Add(currentIP);
}
currentIP = NextIP(currentIP);
}
return ipList;
}
/// <summary>
/// 從一個IPAddress 擷取它的下一個 IPAddress
/// </summary>
/// <param name="theIP">IPAddress</param>
/// <returns></returns>
public IPAddress NextIP(IPAddress theIP)
{
uint startuint = (uint)IPAddress.NetworkToHostOrder((int)theIP.Address);
long NetWorklong = (long)IPAddress.HostToNetworkOrder((int)(startuint + 1));
return new IPAddress(NetWorklong);
}
/// <summary>
/// 判斷IP是否活動
/// </summary>
/// <param name="theIP"></param>
/// <returns></returns>
public bool IpIsLive(IPAddress theIP)
{
System.Net.NetworkInformation.Ping pi = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply pr = pi.Send(theIP);
if ((pr.Status & System.Net.NetworkInformation.IPStatus.Success) == System.Net.NetworkInformation.IPStatus.Success)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 用cmd 判斷IP狀態 (古老的方法,放著紀念)
/// </summary>
/// <param name="theIP"></param>
/// <returns></returns>
public string getIpState(IPAddress theIP)
{
Process pcs = new Process();
pcs.StartInfo.FileName = "cmd.exe";
pcs.StartInfo.UseShellExecute = false;
pcs.StartInfo.RedirectStandardInput = true;
pcs.StartInfo.RedirectStandardOutput = true;
pcs.StartInfo.RedirectStandardError = true;
pcs.StartInfo.CreateNoWindow = true;
string pingStr;
pcs.Start();
pcs.StandardInput.WriteLine("ping -n 1 " + theIP.ToString());
pcs.StandardInput.WriteLine("exit");
string strRst = pcs.StandardOutput.ReadToEnd();
if (strRst.IndexOf("(0% loss)") != -1)
pingStr = "串連";
else if (strRst.IndexOf("Destination host unreachable.") != -1)
pingStr = "無法到達目的主機";
else if (strRst.IndexOf("Request timed out.") != -1)
pingStr = "逾時";
else if (strRst.IndexOf("Unknown host") != -1)
pingStr = "無法解析主機";
else
pingStr = strRst;
pcs.Close();
return pingStr;
}
}
}