2017-03-31 54 views
0

我有一个包含3100个子网(192.168.1.0/24)的导入excel表单为例。我希望能够用存储的变量搜索前3个八位字节。如果我可以得到这个结果,我可以编辑电子表格,只包含他前3个八位字节,并在计划的未来得到我想要的结果。非常感谢你提前。使用3个八位字节(0.0.0)并存储为变量

string octets = ("10.2.30"); 
     var match = false; 

     for (int i = 0; i < xlRange.Rows.Count; i++) 
     { 
      IPAddress excelIP; 

      if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP)) 
      { 

       if (excelIP.ToString().Equals(octets)) 
       { 
        match = true; 
        Console.Write(excelIP.ToString()); 
        Console.WriteLine(" -This id was found"); 
       } 
      } 
     } 
     if (!match) 
     { 
      Console.WriteLine("No Match "); 

     } 

     xlWorkbook.Close(); xlApp = null; 
    } 
+0

10.2.300永远不会匹配一个合法的IP,因为一个字节不能去上述255 –

+0

哎呀,我加了一个额外的0,让我解决这个问题! – gahser1

+1

如果单元格值是CIDR格式,我不认为'IPAddress.TryParse()'会成功。你可能需要做'IPAddress.TryParse(xlWorksheet.Cells [i + 1,1] .Value.Split('/')[0],out excelIP)''。然后你会想用'excelIP.ToString()。StartsWith(octets)',因为你的3字节字符串永远不会匹配4字节的IP字符串。当然,你可能会遇到“192.168.100.1”以“192.168.10”开头的问题,所以你可能会遇到一些不好的命中。 – itsme86

回答

0

这里有几个方法可以做到这一点:

  1. 用句点修改您的octets字符串,并将其匹配到excelIP字符串的开头。
  2. octets字符串拆分为List,并将该列表中的元素与拆分为八位位组列表时的excelIP的元素数相比较。

无论哪种情况,您都需要添加对System.Linq的引用以使用表达式。

using System; 
using System.Linq; 
using System.Net; 

#1:

// add a trailing '.' so we can match the start of the excelIP 
string octets = ("10.2.30."); 
var match = false; 

for (int i = 0; i < xlRange.Rows.Count; i++) 
{ 
    // Get the IP address portion of the CIDR string 
    var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0]; 
    IPAddress excelIP; 

    // If cellString starts with the octets string and it's a valid IP address... 
    if (cellString.StartsWith(octets) && IPAddress.TryParse(cellString, out excelIP)) 
    { 
     match = true; 
     Console.Write(excelIP.ToString()); 
     Console.WriteLine(" -This id was found"); 
    } 
} 

#2:

var match = false; 
string octets = ("10.2.30"); 

string[] octetsToMatch = octets.Split('.'); 

for (int i = 0; i < xlRange.Rows.Count; i++) 
{ 
    // Get the IP address portion of the CIDR string 
    var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0]; 
    IPAddress excelIP; 

    if (IPAddress.TryParse(cellString, out excelIP)) 
    { 
     // Compare the first octets of the IP address with our octetsToMatch 
     if (octetsToMatch.SequenceEqual(cellString.Split('.').Take(octetsToMatch.Length))) 
     { 
      match = true; 
      Console.Write(excelIP.ToString()); 
      Console.WriteLine(" -This id was found"); 
     } 
    } 
} 
+0

在第二个选项中,“SequenceEqual”不会从字符串[] – gahser1

+0

中获取该参数是的 - SequenceEqual采用和IEnumerable,而Take则返回IEnumerable。在我的例子中,'octetsToMatch'和'cellString.Split'的类型都是'string []',所以一切都应该没问题。我用可以验证的一小段代码更新了问题。你遇到了什么错误? –

+0

在第一个选项中,当你到达Console.Writeline(excelIP.ToString()); 它给我一个错误excelIP是一个未分配变量的使用。 – gahser1

相关问题