Solved Efficient way to check all duplicate IPs

Discussion in 'Plugin Development' started by Paul122, Mar 31, 2021.

Thread Status:
Not open for further replies.
  1. Offline

    Paul122

    Hey,

    I'm trying to make a method that returns a list of all players with more than 'x' alts on a given server (an alt being an account on the same IP as another). Currently, I have:

    Code:
    public static List<String> checkAlts(int limit) {
            Map<String, Integer> alts = new HashMap<>();
            for (Player p : Bukkit.getOnlinePlayers()) {
                if (!alts.containsKey(p.getAddress().getHostName())) {
                    alts.put(p.getAddress().getHostName(), 1);
    
                    } else {
                        alts.replace(p.getAddress().getHostName(), alts.get(p.getAddress().getHostName()) + 1);
                    }
                }
            alts.values().removeIf(entries -> entries < limit);
    
            List<String> names = new ArrayList<>();
            for (Player p : Bukkit.getOnlinePlayers()) {
                if (alts.containsKey(p.getAddress().getHostName())) {
                    names.add(p.getName());
                    alts.remove(p.getAddress().getHostName());
                }
            }
            return names;
        }
    This method causes extreme lag and has caused my server to nearly crash twice. Is there a better way to go about doing this that I'm overlooking?
     
  2. Offline

    Strahan

    Maybe I don't understand exactly what you want to do, but if the idea is just to find who has the same IP, an alternative would be to do:
    Code:
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
      Map<String, List<String>> connections = new HashMap<>();
      for (Player p : getServer().getOnlinePlayers()) {
        String ip = p.getAddress().getHostName();
        List<String> people = connections.containsKey(ip)?connections.get(ip):new ArrayList<>();
        people.add(p.getName());
        connections.put(ip, people);
      }
    
      for (Map.Entry<String, List<String>> data : connections.entrySet()) {
        if (data.getValue().size() == 1) continue;
    
        sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&7[&a" + data.getValue().size() + "&7][&a" + data.getKey() + "&7]: &6" + String.join("&7,&6 ", data.getValue())));
      }
      return true;
    }
     
Thread Status:
Not open for further replies.

Share This Page