代码之家  ›  专栏  ›  技术社区  ›  User987

比较IP地址并将其从同一子网中删除

  •  0
  • User987  · 技术社区  · 8 年前

    我有如下用户IP地址列表:

    user 1:
    
    192.168.1.1
    192.168.1.2
    192.168.1.3
    
    
    user 2: 
    
    192.168.1.1
    192.168.1.2
    192.168.1.3
    172.0.0.1
    172.0.0.5
    174.5.5.15
    

    现在我要做的是过滤掉所有明显来自同一子网/来自同一PC/城市的IP。

    这里我只使用本地IP作为示例。

    过滤后,我将留下以下内容:

    对于用户1,每个子网只有一个IP就足够了,如下所示:

    192.168.1.1 => all other IP's would be removed, only one would be left 
       from that specific subnet
    

    用户2:

    192.168.1.1
    172.0.0.1
    174.5.5.15
    

    对于用户2,我只剩下3个IP,从192.168开始。 . 172。 . 有来自该范围的多个IP。

    现在我的想法是使用一个标准来比较IP的前两个数字。例如:

    192.168.0.1
    192.168.0.2
    192.168.0.6
    

    这三个数字前两个数字相同(192.168),因此我可以将它们视为重复的,应该删除它们。只要这些IP中有1个是不相关的,重要的是只剩下1个。

    这将导致留下1个IP,例如:

    192.168.0.1 (again doesn't matter which one is left, just that 1 is left!)
    

    现在到代码部分。我有如下的类结构:

    public class SortedUser
    {
        public string Email { get; set; }
    
        public List<IpInfo> IPAndCountries = new List<IpInfo>();
    
    }
    

    而ipinfo类如下所示:

       public class IpInfo
        {
    
            public string Ip { get; set; }
    
        }
    

    现在有人能帮我吗?我怎样才能以最简单的方式做到这一点?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Kami    8 年前

    SortedUser user = new SortedUser()
    {
        Email = "Foo@bar.com",
        IPAndCountries = new List<IpInfo>()
        {
            new IpInfo() {Ip = "192.168.0.1"},
            new IpInfo() {Ip = "192.168.1.2"},
            new IpInfo() {Ip = "193.168.3.2"},
            new IpInfo() {Ip = "8.2.4.5"}
        }
    };
    
    // Using ToArray to avoid collection modified errors
    foreach (IpInfo item in user.IPAndCountries.ToArray())
    {
    
        string[] ipSplit = item.Ip.Split('.');
    
        string prefix = $"{ipSplit[0]}.{ipSplit[1]}";
        user.IPAndCountries.RemoveAll(info => info.Ip.StartsWith(prefix) && info.Ip != item.Ip);
    }