java讀取電腦IP地址
兩種方法:第一種程式碼量比較少,但是不支援linux系統。第二種支援linux系統,但是程式碼量比較大。實際用的時候自己根據需要選擇吧。現在將程式碼分別貼出來供大家參考。
第一種:
inet = InetAddress.getLocalHost();
String ipStrs = inet.getHostAddress();
System.out.println(ipStrs);
第二種:
Enumeration allNetInterfaces;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements())
{
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements())
{
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address)
{
System.out.println("本機的IP = " + ip.getHostAddress());
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}