Files
Backend/src/main/java/cc.fascinated/common/DNSUtils.java

58 lines
1.7 KiB
Java
Raw Normal View History

2024-04-10 07:43:38 +01:00
package cc.fascinated.common;
2024-04-10 16:21:07 +01:00
import cc.fascinated.model.dns.impl.ARecord;
import cc.fascinated.model.dns.impl.SRVRecord;
2024-04-10 07:43:38 +01:00
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
2024-04-10 16:21:07 +01:00
import org.xbill.DNS.Lookup;
2024-04-10 07:43:38 +01:00
import org.xbill.DNS.Record;
2024-04-10 16:21:07 +01:00
import org.xbill.DNS.Type;
2024-04-10 07:43:38 +01:00
/**
* @author Braydon
*/
@UtilityClass
public final class DNSUtils {
private static final String SRV_QUERY_PREFIX = "_minecraft._tcp.%s";
/**
2024-04-10 16:21:07 +01:00
* Get the resolved address and port of the
* given hostname by resolving the SRV records.
2024-04-10 07:43:38 +01:00
*
* @param hostname the hostname to resolve
2024-04-10 16:21:07 +01:00
* @return the resolved address and port, null if none
2024-04-10 07:43:38 +01:00
*/
@SneakyThrows
2024-04-10 16:21:07 +01:00
public static SRVRecord resolveSRV(@NonNull String hostname) {
2024-04-10 07:43:38 +01:00
Record[] records = new Lookup(SRV_QUERY_PREFIX.formatted(hostname), Type.SRV).run(); // Resolve SRV records
if (records == null) { // No records exist
return null;
}
2024-04-10 16:21:07 +01:00
SRVRecord result = null;
2024-04-10 07:43:38 +01:00
for (Record record : records) {
2024-04-10 16:21:07 +01:00
result = new SRVRecord((org.xbill.DNS.SRVRecord) record);
2024-04-10 07:43:38 +01:00
}
2024-04-10 16:21:07 +01:00
return result;
2024-04-10 07:43:38 +01:00
}
/**
2024-04-10 16:21:07 +01:00
* Get the resolved address of the given
* hostname by resolving the A records.
2024-04-10 07:43:38 +01:00
*
* @param hostname the hostname to resolve
2024-04-10 16:21:07 +01:00
* @return the resolved address, null if none
2024-04-10 07:43:38 +01:00
*/
@SneakyThrows
2024-04-10 16:21:07 +01:00
public static ARecord resolveA(@NonNull String hostname) {
2024-04-10 07:43:38 +01:00
Record[] records = new Lookup(hostname, Type.A).run(); // Resolve A records
if (records == null) { // No records exist
return null;
}
2024-04-10 16:21:07 +01:00
ARecord result = null;
2024-04-10 07:43:38 +01:00
for (Record record : records) {
2024-04-10 16:21:07 +01:00
result = new ARecord((org.xbill.DNS.ARecord) record);
2024-04-10 07:43:38 +01:00
}
2024-04-10 16:21:07 +01:00
return result;
2024-04-10 07:43:38 +01:00
}
}