1. inetAddress類
通過InetAddress的實例對象包含以數字形式保存的IP地址,同時還可能包含主機名(如果使用主機名來獲取InetAddress的實例,或者使用數字來構造,並且啓用了反向主機名解析的功能)。InetAddress類提供了將主機名解析爲IP地址(或反之)的方法。其生成InetAddress對象的方法
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) throws UnknownHostException {
//Inet4Address address= (Inet4Address) Inet4Address.getLocalHost();
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);//獲取計算機名稱和ip地址
String hostAddress = address.getHostAddress();
System.out.println(hostAddress);//獲取ip地址
String hostName = address.getHostName();
System.out.println(hostName);//獲取計算機名稱
}
}
2.封裝方法
public static String getLocalIp() {
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface nif = netInterfaces.nextElement();
Enumeration<InetAddress> InetAddress = nif.getInetAddresses();
while (InetAddress.hasMoreElements()) {
String ip = InetAddress.nextElement().getHostAddress();
if (ip.startsWith("192.168")) {
return ip;
}
}
}
} catch (SocketException e) {
}
return "127.0.0.1";
}