[TOC]
Describe
Since the project is deployed on the cluster, it is necessary for the project to automatically collect information from each machine. Java.net.InetAddress.getLocalHost () to obtain the IP and machine name information for the local machine, but found that the actual IP and machine name information for the machine could not be obtained under Linux (obtained by localhost/127.0.0.1).
Scenario Description
Depending on the system type (Linux, Windows), the IP information of the local machine is obtained in different ways.
Get IP under Windows
java.net.InetAddress.getLocalHost().getHostAddress();
Get the IP under Linux
/*** Get the IP address under Linux * * @returnIP Address * @throws socketexception */ Private StaticStringGetlinuxlocalip()throwssocketexception {String IP ="";Try{ for(Enumeration<networkinterface> en = networkinterface.getnetworkinterfaces(); En.hasmoreelements();) {NetworkInterface intf = en.nextelement(); String name = intf.GetName();if(!name.contains("Docker") &&!name.contains("Lo")) { for(enumeration<inetaddress> enumipaddr = intf.getinetaddresses(); Enumipaddr.hasmoreelements();) {inetaddress inetaddress = enumipaddr.nextelement();if(!inetaddress.isloopbackaddress()) {String IPAddress = inetaddress.gethostaddress().toString();if(!ipaddress.contains("::") &&!ipaddress.contains("0:0:") &&!ipaddress.contains("FE80") {IP = ipaddress; } } } } } }Catch(SocketException ex) {IP ="127.0.0.1"; Ex.Printstacktrace(); }returnip }
Determine the type of operating system
/** * Judging operating system is No is Windows * * @return */
public
static
boolean
() {boolean Iswindowsos = false ; //Note: The system here refers to the JRE (runtime) systems, not the OS String osname = System. getproperty ( "Os.name" ); if (Osname. tolowercase (). indexof ( "Windows" ) >-1 ) {Iswindowsos = true; } return Iswindowsos; }
Here is a description of System.getproperty ("Os.name") (refer to from http://blog.csdn.net/brotherdong90/article/details/49073941)
Key |
Notes |
File.separator |
File separator (e.g., "/") |
Java.class.path |
Java Classpath |
Java.class.version |
Java class version number |
Java.home |
Java installation directory |
Java.vendor |
Java vendor-specific String |
Java.vendor.url |
Java Vendor URL |
Java.version |
Java Version number |
Line.separator |
Line Separator |
Os.arch |
Operating System Architecture |
Os.name |
Operating system Name |
Path.separator |
Path separator (e.g., ":") |
User.dir |
User ' s current working directory |
User.home |
User Home Directory |
User.Name |
User account Name |
Finally, the above three methods are integrated
/** * 获取本地IP地址 * * @throws SocketException */ publicstaticgetLocalIPthrows UnknownHostException, SocketException { if (isWindowsOS()) { return InetAddress.getLocalHost().getHostAddress(); else { returngetLinuxLocalIp(); } }
Reference
Https://www.cnblogs.com/raphael5200/p/5996464.html
Java gets the IP of this machine (Linux and Windows)