使用 3 个八位字节 (0.0.0) 并存储为变量

Using 3 octets (0.0.0) and storing as a variable

我有一个导入的 excel sheet 有 3100 个子网 (192.168.1.0/24) 作为例子。我希望能够使用存储的变量搜索前 3 个八位字节。如果我能做到这一点,我可以编辑 spreadsheet 以仅包含他的前 3 个八位字节,并在程序的未来获得我想要的结果。非常感谢您。

 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;
    }

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

  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");
        }
    }
}