背景
Java 通过计算机名获取 IP 地址;或者通过 IP 地址获取计算机名。
实现
package itheima;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getByName("HostNameOrIP"); // 此处可以是计算机名或者IP,任一即可
String name = address.getHostName();
String ip = address.getHostAddress();
System.out.println("主机名:" + name);
System.out.println("IP地址:" + ip);
}
}