InetAddress
2019-07-09 22:33 更新
InetAddress测试: 解决ip地址问题。
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Test {
public static void main(String[] args) throws UnknownHostException {
/**
* InetAddress没有封装端口
*/
//使用getLocalHost方法创建InetAddress对象
InetAddress address = InetAddress.getLocalHost();
System.out.println(address.getHostAddress());//返回本机的ip地址
System.out.println(address.getHostName());//输出本机计算机名
//根据域名得到InetAddress对象
address = InetAddress.getByName("www.163.com");
System.out.println(address.getHostAddress());//输出163服务器的ip:125.39.21.3
System.out.println(address.getHostName());//输出域名:www.163.com
//根据ip得到InetAddress对象
address = InetAddress.getByName("125.39.21.3");
System.out.println(address.getHostAddress());//输出163服务器的ip:125.39.21.3
System.out.println(address.getHostName());//如果ip被解析(DNS)则输出域名,如果没被解析则输出ip。
}
}
以上内容是否对您有帮助:
← 基本概念
更多建议: