2017-05-16 285 views
0

我正在製作一個應用程序,並且爲了獲得其中一個功能,我需要獲取我的網絡的ip地址。從arp獲取IP地址

ping 192.168.1.255 & arp-a會列出每個IP地址,我需要在表格的格式:

Internet Address  Physical Address  Type 

    192.168.x.x   xx-xx-xx-xx-xx-xx  dynamic 
    192.168.x.x   xx-xx-xx-xx-xx-xx  dynamic 

代碼爲是這樣的:

private void button_Click(object sender, EventArgs e) 
     { 

       string strCmdText3; 
       strCmdText3 = "/c ping 192.168.1.255 & arp -a"; 

       Process process = new Process(); 
       process.StartInfo.FileName = "cmd.exe"; 
       process.StartInfo.Arguments = strCmdText3; 
       process.StartInfo.UseShellExecute = false; 
       process.StartInfo.RedirectStandardOutput = true; 
       process.StartInfo.RedirectStandardError = true; 
       process.StartInfo.CreateNoWindow = true; 
       process.Start(); 
       //* Read the output (or the error) 
       string output = process.StandardOutput.ReadToEnd(); 
       //Console.WriteLine(output); 
       //string err = process.StandardError.ReadToEnd(); 
       //Console.WriteLine(err); 
       process.WaitForExit(); 

       show.Text = output; 
      } 

現在我不知道是怎麼能我只獲得IP地址(將它們放入數組或其他東西),所以稍後可以使用它們來執行不同的命令。

這怎麼搞會

"\r\nPinging 192.168.1.255 with 32 bytes of data:\r\nRequest timed out.\r\nRequest timed out.\r\nRequest timed out.\r\nRequest timed out.\r\n\r\nPing statistics for 192.168.1.255:\r\n Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),\r\n\r\nInterface: 10.10.10.74 --- 0x7\r\n Internet Address  Physical Address  Type\r\n 10.10.80.1   10-da-43-72-3a-99  dynamic \r\n 10.10.80.335   00-e0-4c-c7-44-0c  dynamic \r\n 10.10.80.290   e0-ac-cb-60-88-c4  dynamic \r\n 10.10.80.25   34-02-86-a0-79-72  dynamic \r\n 10.10.80.27   00-1c-c0-8a-59-e7  dynamic \r\n 
+0

「字符串輸出」變量的一個確切的例子是hellowful。 – pijemcolu

回答

0
  • 刪除了PING命令,你可以添加回去,但更多的行後跳過。
  • 斯普利特返回文本的換行字符
  • 搶串[]和修剪字符每行3-18投入列表

在大多數情況下有非常小的需要,這裏是更新的代碼

static void Main() { 
    string strCmdText3; 
    strCmdText3 = "/c arp -a"; 

    Process process = new Process(); 
    process.StartInfo.FileName = "cmd.exe"; 
    process.StartInfo.Arguments = strCmdText3; 
    process.StartInfo.UseShellExecute = false; 
    process.StartInfo.RedirectStandardOutput = true; 
    process.StartInfo.RedirectStandardError = true; 
    process.StartInfo.CreateNoWindow = true; 
    process.Start(); 
    //* Read the output (or the error) 
    string output = process.StandardOutput.ReadToEnd(); 
    //Console.WriteLine(output); 
    //string err = process.StandardError.ReadToEnd(); 
    //Console.WriteLine(err); 
    process.WaitForExit(); 

    //show.Text = output; 

    string[] LinesReturned = output.Split('\n'); 
    List<string> ipAddresses = new List<string>(); 
    for (int i = 3; i < LinesReturned .GetUpperBound(0); i++) { 
    ipAddresses.Add(LinesReturned [i].Substring(2, 15).Trim()); 
} 
+0

不錯,非常感謝! – Alexander