Java obtains the host IP address and automatically distinguishes between windows and Linux

import java. net. InetAddress; import java. net. NetworkInterface; import java. util. Enumeration;

public class OSUtil {

/*** judge whether the current operation is windows. * *@ Return true --- is the windows operating system * / public static Boolean iswindowsos() {Boolean iswindowsos = false; string osname = system. Getproperty ("OS. Name"); if (osname. Tolowercase(). Indexof ("windows") > - 1) {iswindowsos = true;} return isWindowsOS; } /** * Obtain the local IP address and automatically distinguish between windows and Linux operating systems * @ return string * / public static string getlocalip() {string SIP = ""; InetAddress IP = null; try {/ / if it is a Windows operating system if (iswindowsos()) {IP = InetAddress. Getlocalhost();}// For Linux operating system else {Boolean bfindip = false; enumeration < networkinterface > netinterfaces = (enumeration < networkinterface >) networkinterface. Getnetworkinterfaces(); while (netinterfaces. Hasmoreelements()) {if (bfindip) {break;} NetworkInterface ni = (NetworkInterface) netInterfaces. nextElement(); //---------- In specific cases, Ni can be considered Getname determination / / traverse all IP enumeration < InetAddress > IPS = Ni getInetAddresses(); While (IPS. Hasmoreelements()) {IP = (InetAddress) IPS. Nexterelement(); if (IP. Issitelocaladdress() & &! IP. Isloopbackaddress() / / 127. Lookback address & & IP. Gethostaddress(). Indexof (":") = = - 1) {bfindip = true; break;}}

} } } catch (Exception e) { e.printStackTrace(); }

if(null != ip){ sIP = ip.getHostAddress(); } return sIP; } // If the requirements cannot be met, please leave a message and explain the situation. Public static void main (string [] args) {string ServerIP = OS. Getlocalip(); system. Out. Println ("ServerIP::" + ServerIP);}}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>