c# - 从本地网络C#获取所有IP时出现问题
问题描述
我在互联网上尝试了很多从本地网络获取 IP 的解决方案,但所有这些解决方案都未能获取所有 IP。我也尝试使用 ARP 命令“arp /a”和“arp -a”来获取 IP,但是在搜索了一段时间后,这个命令也无法完成这项工作,我找到了一个名为“Advance IP Scanner”的软件,当我运行这个软件它从本地网络获取所有IP,对我来说最奇怪的是,在运行高级IP扫描器后,当我运行ARP命令“arp /a”或“arp -a”时,它会从我的本地获取所有IP网络。
这是我尝试过的。
public List<IPScanEntity> GetArpResult()
{
List<IPScanEntity> List = new List<IPScanEntity>();
string baseIp = ConfigurationManager.AppSettings["baseIp"];
//getting my own system IP
List.Add(HostIPScanResult());
for (int subnet = 1; subnet < 255; subnet++)
{
bool a = List.Any(x => x.Ip.Equals(baseIp+subnet.ToString()));
if (a == true)
{
continue;
}
try
{
var p = Process.Start(new ProcessStartInfo("arp", "/a " + baseIp + subnet)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
});
var output = p?.StandardOutput.ReadToEnd();
p?.Close();
var lines = output.Split('\n').Where(l => !string.IsNullOrWhiteSpace(l));
if (!lines.Contains("No ARP Entries Found.\r"))
{
var result =
(from line in lines
select Regex.Split(line, @"\s+")
.Where(i => !string.IsNullOrWhiteSpace(i)).ToList()
into items
where items.Count == 3
select new IPScanEntity
{
Ip = items[0],
MacAddress = items[1],
});
List.Add(result.FirstOrDefault());
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
return List;
}
解决方案
arp 的问题在于它只列出了您的系统知道的 IP 地址(它已经与之通信)。
如果您真的想获取所有 IP,您应该为您的子网循环 ping。(例如,请参阅Mikael 发布的链接)
编辑 1)
如果 ICM 协议被机器阻止(默认启用)并且您知道一个打开的端口,您可以使用PPing 之类的工具来 ping 特定的 tcp/udp 端口。也许还有其他一些我不知道的带有 api 或 exitcode 支持的工具,如果没有,您可以使用我为 ping 编写的这个包装器:
public static bool PPing(string host, int port, PPingProtocolType type = PPingProtocolType.tcp)
{
var cmdOutput = new StringBuilder();
var cmdStartInfo = new ProcessStartInfo()
{
//Path to PPing.exe
FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tools", "pping.exe"),
Arguments = $"-r 1 -w 0{(type == PPingProtocolType.udp ? " -u " : " ")}{host} {port}",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
};
using (Process proc = Process.Start(cmdStartInfo))
{
while (!proc.StandardOutput.EndOfStream)
{
cmdOutput.AppendLine(proc.StandardOutput.ReadLine());
}
}
return cmdOutput.ToString().Contains("(1 OPEN, 0 CLOSED)");
}
public enum PPingProtocolType
{
tcp = 0,
udp = 1,
}
推荐阅读
- java - 如何在 netbeans 12.4 中启用本机打包
- pine-script - 如何在松纸上玩弄 SMA 的时间框架?
- amazon-web-services - 在 AWS ElasticBeanstalk 上使用 .ebextensions 为 SQL Server 安装 Microsoft ODBC Driver 17 时出现问题
- mysql - 如何选择缺少特定类型行的记录
- c# - 我如何遍历字符串数据类型的日期列表以将每个日期传递给 sqlcommand 以将表中的行获取到 datagridview
- gf - 尝试在 GF 中使用依赖类型时出现语法错误
- python-3.x - Python 模块和 Python 面向对象的概念有什么区别?
- java - Java 11 HTTP API WebSocket 客户端抛出 java.net.SocketException:连接重置
- html - 移动设备上的图像损坏
- node.js - 如何通过 id 在对象数组中查找?