How do I get the local hostname if unresolvable through DNS in Java?

后端 未结 8 2482
清酒与你
清酒与你 2021-02-19 04:38

This sounds like something that should have been asked before, and it has sort of, but I\'m looking to get the local hostname and IP addresses of a machine even when it is not r

8条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 05:13

    Alternatively, use JNA to call the gethostname function on unixes, avoiding the reverse DNS lookup.

    Some notes: on Linux, I believe gethostname simply calls uname and parses the output. On OS X the situation is more complex, as your hostname can be affected by DNS, but those side-effects aside, it's definitely what I get from hostname.

    import com.sun.jna.LastErrorException
    import com.sun.jna.Library
    import com.sun.jna.Native
    
    ...
    
    private static final C c = (C) Native.loadLibrary("c", C.class);
    
    private static interface C extends Library {
        public int gethostname(byte[] name, int size_t) throws LastErrorException;
    }
    
    public String getHostName() {
        byte[] hostname = new byte[256];
        c.gethostname(hostname, hostname.length)
        return Native.toString(hostname)
    }
    

    jna-platform.jar includes Win32 functions, so there it's as simple as a call to Kernel32Util.getComputerName().

提交回复
热议问题