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";
}