| 1 | package net.minecraft.client.multiplayer.resolver;
|
| 2 |
|
| 3 | import com.google.common.net.HostAndPort;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import java.net.IDN;
|
| 6 | import net.fabricmc.api.EnvType;
|
| 7 | import net.fabricmc.api.Environment;
|
| 8 | import org.jspecify.annotations.Nullable;
|
| 9 | import org.slf4j.Logger;
|
| 10 |
|
| 11 | @Environment(EnvType.CLIENT)
|
| 12 | public final class ServerAddress {
|
| 13 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 14 | private final HostAndPort hostAndPort;
|
| 15 | private static final ServerAddress INVALID = new ServerAddress(HostAndPort.fromParts("server.invalid", 25565));
|
| 16 |
|
| 17 | public ServerAddress(final String host, final int port) {
|
| 18 | this(HostAndPort.fromParts(host, port));
|
| 19 | }
|
| 20 |
|
| 21 | private ServerAddress(final HostAndPort hostAndPort) {
|
| 22 | this.hostAndPort = hostAndPort;
|
| 23 | }
|
| 24 |
|
| 25 | public String getHost() {
|
| 26 | try {
|
| 27 | return IDN.toASCII(this.hostAndPort.getHost());
|
| 28 | } catch (IllegalArgumentException ignored) {
|
| 29 | return "";
|
| 30 | }
|
| 31 | }
|
| 32 |
|
| 33 | public int getPort() {
|
| 34 | return this.hostAndPort.getPort();
|
| 35 | }
|
| 36 |
|
| 37 | public static ServerAddress parseString(final @Nullable String input) {
|
| 38 | if (input == null) {
|
| 39 | return INVALID;
|
| 40 | }
|
| 41 |
|
| 42 | try {
|
| 43 | HostAndPort result = HostAndPort.fromString(input).withDefaultPort(25565);
|
| 44 | return result.getHost().isEmpty() ? INVALID : new ServerAddress(result);
|
| 45 | } catch (IllegalArgumentException e) {
|
| 46 | LOGGER.info("Failed to parse URL {}", input, e);
|
| 47 | return INVALID;
|
| 48 | }
|
| 49 | }
|
| 50 |
|
| 51 | public static boolean isValidAddress(final String input) {
|
| 52 | try {
|
| 53 | HostAndPort hostAndPort = HostAndPort.fromString(input);
|
| 54 | String host = hostAndPort.getHost();
|
| 55 | if (!host.isEmpty()) {
|
| 56 | IDN.toASCII(host);
|
| 57 | return true;
|
| 58 | }
|
| 59 | } catch (IllegalArgumentException var3) {
|
| 60 | }
|
| 61 |
|
| 62 | return false;
|
| 63 | }
|
| 64 |
|
| 65 | public static int parsePort(final String str) {
|
| 66 | try {
|
| 67 | return Integer.parseInt(str.trim());
|
| 68 | } catch (Exception var2) {
|
| 69 | return 25565;
|
| 70 | }
|
| 71 | }
|
| 72 |
|
| 73 | @Override
|
| 74 | public String toString() {
|
| 75 | return this.hostAndPort.toString();
|
| 76 | }
|
| 77 |
|
| 78 | @Override
|
| 79 | public boolean equals(final Object o) {
|
| 80 | if (this == o) {
|
| 81 | return true;
|
| 82 | } else {
|
| 83 | return o instanceof ServerAddress serverAddress ? this.hostAndPort.equals(serverAddress.hostAndPort) : false;
|
| 84 | }
|
| 85 | }
|
| 86 |
|
| 87 | @Override
|
| 88 | public int hashCode() {
|
| 89 | return this.hostAndPort.hashCode();
|
| 90 | }
|
| 91 | }
|
| 92 |
|