2017-03-17 77 views
2

我想要获取我的网络上连接的所有计算机的列表,并且我能够这样做。如何从字符串中分离数据

但是,然后我需要获取我以String格式存储的Ip地址的Hostanme以及其他一些数据,例如mac地址。

我尝试过使用json但是无法从字符串中获取Ip列表。我只列出从字符串的IP,这样使用的foreach我能找到在特定的主机名的

这里是代码:

static void Main(String[] args) 
    { 
     Process arp = new Process(); 
     arp.StartInfo.UseShellExecute = false; 
     arp.StartInfo.RedirectStandardOutput = true; 
     arp.StartInfo.FileName = "C://Windows//System32//cmd.exe"; 
     arp.StartInfo.Arguments = "/c arp -a"; 
     arp.StartInfo.RedirectStandardOutput = true; 
     arp.Start(); 
     arp.WaitForExit(); 
     string output = arp.StandardOutput.ReadToEnd(); 
     Console.WriteLine(output); 

     Console.WriteLine(data.Internet_Address); 
     Console.ReadLine();    
    } 
} 

这里是输出:

enter image description here

+0

请以文本形式添加输入和所需的输出而不是图像。 – Adil

+0

这是(** data.Internet_Address **)从哪里来的? –

+0

为什么不能直接获取这些信息而不是调用命令行工具并解析其输出? –

回答

1

您可以使用正则表达式使用提取的IP Regex.Matches

var matches1 = Regex.Matches(output, @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");  

作为您可能不需要的第一个IP,您可以跳过它。

for(int i=1; i < matches1.Count; i++) 
    Console.WriteLine("IPs " + i + "\t" + matches1[i].Value); 
+0

非常感谢!它工作的Adil我努力使用Json,它从来没有打我使用正则表达式 –

+0

不客气。 – Adil

0

通常会使用正则表达式来解析这些文本。或者,您可以获取CSV库来解析类似的格式,或者如果这只是基本的String.Split将会执行的一次性案例。

var byLine = output.Split('\n') // split into lines 
    .Skip(1); // skip header 
var ips = byLine.Select(s => s.Split(' ')[0]); 

注:

  • 很可能更好地得到您被直接调用,而不是调用命令行工具
  • 本地地址一般没有“主机名”寻找信息。 Windows机器名称不必作为DNS条目可见。