import java.net.InetAddress;
/**
* 网络通信的一个要素:IP地址,通过IP地址,唯一的定位互联网上一台主机
*
* InetAddress位于java.net包下
*InetAddress用来代表IP地址,一个该对象就代表一个IP地址
*1.如何创建InetAddress的对象,getByName(String host);
*2.getHostName();获取了域名
*3.getHostAddress();获取了IP地址
*
*/
public class TestInetAddress {
public static void main(String[] args) throws Exception {
InetAddress inet = InetAddress.getByName("www.atguigu.com");
System.out.println("inet==>"+inet);
//两个方法
System.out.println("inet.getHostName()==>"+inet.getHostName());
System.out.println("inet.getHostAddress()==>"+inet.getHostAddress());
//获取本机ip:getLocalhost();
InetAddress inet1 = InetAddress.getLocalHost();
System.out.println("inet1==>"+inet1);
System.out.println("inet1.getHostName()==>"+inet1.getHostName());
System.out.println("inet1.getHostAddress()==>"+inet1.getHostAddress());
}
}
打印结果是:
inet==>www.atguigu.com/42.121.6.2
inet.getHostName()==>www.atguigu.com
inet.getHostAddress()==>42.121.6.2
inet1==>lixiumingdeMacBook-Air.local/192.168.2.102
inet1.getHostName()==>lixiumingdeMacBook-Air.local
inet1.getHostAddress()==>192.168.2.102