遍历IP段,返回活动 IP 列表
小Lee闲暇时间钻牛角尖,写了一个不操作IP字符串的遍历IP段并返回活动IP列表的方法
小Lee闲暇时间钻牛角尖,写了一个不操作IP字符串的遍历IP段并返回活动IP列表的方法,闲话就不说了,直接贴CODE
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
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;
}
}
}