/gethostname4j

Simple JNA library to get the current machine's hostname from Java

Primary LanguageJavaMIT LicenseMIT

gethostname4j

Simple JNA library to get the current machine's hostname from Java

I was frustrated to find that the common-ish Java idiom of InetAddress.getLocalHost().getHostName() was returning localhost in some cases that only seemed solved by tinkering with /etc/hosts. This library uses JNA to directly call the C library's gethostname method (or Kernel32Util.getComputerName() on Windows), and gives you back the hostname it got.

You can get it from maven central with a dependency like this...

    <dependency>
        <groupId>com.kstruct</groupId>
        <artifactId>gethostname4j</artifactId>
        <version>1.0.0</version>
    </dependency>

or

compile 'com.kstruct:gethostname4j:1.0.0'

in Gradle

...and then use it in your code to get the hostname with something like...

    import com.kstruct.gethostname4j.Hostname;
    
    ...
    
    String hostname = Hostname.getHostname();

See also

Build/Test

Linux Java 11 CI Mac Java 11 CI Windows Java 11 CI Linux Java 8 CI