Skip to content

Commit

Permalink
fix: obtain the correct IP address for the static worker (#306)
Browse files Browse the repository at this point in the history
  • Loading branch information
mycxu authored Oct 23, 2024
1 parent 69e6ba3 commit feb93c9
Showing 1 changed file with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.net.InetAddress;
import java.time.Duration;
import java.time.Instant;
import java.net.*;
import java.util.Enumeration;

@StaticWorker
@Component
Expand All @@ -50,8 +52,7 @@ public CurrentStaticWorker(StaticWorkerRepo staticWorkerRepo,

@PostConstruct
private void init() throws IOException {
InetAddress localHost = InetAddress.getLocalHost();
String hostAddress = localHost.getHostAddress();
String hostAddress = getLocalHostExactAddress();
current = this.staticWorkerRepo.findByHostAddress(hostAddress).orElseGet(() -> {
StaticWorkerEntity worker = new StaticWorkerEntity();
worker.setHostAddress(hostAddress);
Expand All @@ -78,4 +79,21 @@ private void updateStorageSpace() throws IOException {
current.setTotalSpace(storageService.getTotalSpace());
current = staticWorkerRepo.save(current);
}

private String getLocalHostExactAddress() throws IOException {
Enumeration<NetworkInterface> allNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = allNetworkInterfaces.nextElement();
if (!networkInterface.isLoopback() && !networkInterface.isVirtual() && networkInterface.isUp()) {
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress inetAddress = addresses.nextElement();
if (inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
}
return InetAddress.getLocalHost().getHostAddress();
}
}

0 comments on commit feb93c9

Please sign in to comment.