Skip to content

Commit

Permalink
Improve getting the Hostname for _host/Hostname Channel
Browse files Browse the repository at this point in the history
(cherry picked from commit bdd2d1e)
  • Loading branch information
sfeilmeier committed May 6, 2021
1 parent f700d03 commit 2ab79dd
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions io.openems.edge.core/src/io/openems/edge/core/host/HostImpl.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package io.openems.edge.core.host;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;

import org.osgi.framework.BundleContext;
Expand Down Expand Up @@ -75,9 +77,13 @@ public HostImpl() {

// Initialize 'Hostname' channel
try {
this._setHostname(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
this._setHostname(HostImpl.execReadToString("hostname"));
} catch (IOException e) {
try {
this._setHostname(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
}
}

Expand Down Expand Up @@ -189,4 +195,17 @@ protected void logWarn(Logger log, String message) {
protected void logError(Logger log, String message) {
super.logError(log, message);
}

/**
* Source: https://stackoverflow.com/a/28043703.
*
* @param execCommand the command
* @return the parsed result
* @throws IOException
*/
private static String execReadToString(String execCommand) throws IOException {
try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) {
return s.hasNext() ? s.next().trim() : "";
}
}
}

0 comments on commit 2ab79dd

Please sign in to comment.