InetAddress对象应用的测试。获取本机地址并转换成字符串输出,输出本机主机名和IP地址以及通过局域网内计算机的名字得到它的IP地址。
import java.net.*;
public class FindHost {
public static void main(String[] args) {
try {
InetAddress h = InetAddress.getLocalHost(); //本机地址
System.out.println("toString():" + h.toString()); //转换为字符串类型
System.out.println("getHostName():" + h.getHostName()); //名字
System.out.println("getHostAddress():" + h.getHostAddress()); //IP地址
h = InetAddress.getByName("engine"); //通过名字获得局域网内的另一台主机信息,此处无名字为engine的主机
System.out.println(h.getHostName() + ":" + h.getHostAddress());
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
}
}
}
运行结果: