Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: obtain the correct IP address for the static worker #306

Merged
merged 5 commits into from
Oct 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
}
Loading