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

后端 未结 8 2481
清酒与你
清酒与你 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:17

    Java will read the /etc/hosts file if there is no DNS configured, or rather the corresponding C functions will.

    0 讨论(0)
  • 2021-02-19 05:18

    If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.

    https://github.com/mattsheppard/gethostname4j

    (I think it's almost exactly what @danny-thomas proposed, but maybe more convenient if you're already using Maven ;)

    0 讨论(0)
提交回复
热议问题