【问题标题】:Comparing IP's addresses and removing the ones from the same subnet比较 IP 地址并从同一子网中删除这些地址
【发布时间】:2018-08-08 08:16:27
【问题描述】:

我有一个用户 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/City 的 IP。

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

过滤后我会留下以下内容:

对于用户 1,每个子网只有 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,我从 192.168 开始就剩下 3 个 IP。. 和 172.0.. 在该范围内有多个 IP。

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

192.168.0.1
192.168.0.2
192.168.0.6

这 3 个具有相同的前两个数字 (192.168),因此我可以认为它们是重复的,应该将它们删除。这些 IP 中的哪一个留在这里是无关紧要的,重要的是只剩下 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; }

    }

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

【问题讨论】:

  • 当您说从同一子网中删除所有内容时,您需要考虑您正在应用的子网掩码。请参阅subnet-calculator.com - 您能否添加注释以说明您希望删除哪些子网?
  • @Kami Sry 也许我表达自己错了......我们只是说所有具有相同前两个数字的 ip 都应该被删除,并且只剩下其中的 1 个。忽略子网和所有这些......
  • @Kami 不,它不是重复的......我只想从我的列表中删除前两个数字相同的相同 ip,如果这样更容易说的话......

标签: c# asp.net asp.net-mvc c#-4.0 c#-3.0


【解决方案1】:

如果您只查找地址列表中的前两个字节,您可以像这样运行字符串比较(未测试):

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

【讨论】:

  • 嘿 Kami,它在删除部分说: Remove(p=>p.StartsWith(prefix) && p != ipToSearchFor) following : 无法将 lambda 表达式转换为类型“IpInfo”,因为它不是一个代表?
  • @User987 已更正 - 在前面的代码中,我将对象本身与字符串进行比较,而不是 Ip 属性。
  • 由于某种原因它仍然显示相同的错误=/
  • 或者:var Range = IpAndCountries.where(p=>p.Ip.StartsWith(prefix) && p.Ip != ipToSearchFor).ToList() 然后是 IpAndCountries.RemoveRange(Range); ?
  • @User987 我无权访问 VS atm,但您应该可以根据自己的需要进行调整。
猜你喜欢
  • 2021-01-10
  • 2010-11-04
  • 2012-08-26
  • 2018-11-24
  • 2013-07-02
  • 1970-01-01
  • 2021-12-12
  • 2012-10-20
  • 2014-08-04
相关资源
最近更新 更多