1.InetAddress
封装域名和地址,不包含端口信息
获取对象的方法,没有对外开放的构造方法,因此通过返回InetAddress对象的静态方法进行实例化
InetAddress.getLocalHost();
InetAddress.getByName("www.abc.com");//域名
InetAddress.getByName("223.1.45.67");//地址
InetAddress.getLocalHost();//获取本地地址
2.InetSocketAddress
封装域名/端口/地址
提供构造方法创建对象
InetSocketAddress(String hostname, int port) 指定域名,端口号
InetSocketAddress(InetAddress addr, int port) 指定地址,端口号
常用方法
getAddress()
getHostName()
getPort()
InetAddress类
/**
* 封装域名和地址,不包含端口信息
获取对象的方法,没有对外开放的构造方法,因此通过返回InetAddress对象的静态方法进行实例化
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TInetAddress {
public static void main(String[] args) throws UnknownHostException {
//通过InetAddress.getLocalHost();方法获取InetAddress对象
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostName());//获取计算机名
System.out.println(addr.getHostAddress());//获取本地地址
//通过InetAddress.getByName();方法获取InetAddress对象
InetAddress addr1 = InetAddress.getByName("www.alibaba.com");
System.out.println(addr1.getHostName());//获取域名
System.out.println(addr1.getHostAddress());//获取阿里巴巴的Ip地址
//通过InetAddress.getByName();方法获取InetAddress对象
InetAddress addr2 = InetAddress.getByName("192.168.102.195");
System.out.println(addr2.getHostName());//Ip地址存在且DNS允许解析则输出相应域名,否则返回"192.168.102.195"
System.out.println(addr2.getHostAddress());//输出Ip地址
}
}
InetSocketAddress
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class TInetSocketAddress {
public static void main(String[] args) throws UnknownHostException {
//创建对象
/**
* InetSocketAddress(String hostname, int port)方法内封装了解析hostname的方法,将"localhost"
* 解析为InetAddress对象,同创建对象2的方法InetSocketAddress(InetAddress addr, int port)
*/
InetSocketAddress address = new InetSocketAddress("localhost", 9999);
//创建对象2
InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9998);
System.out.println(address.getHostName());//获取计算机名称
System.out.println(address.getPort());//端口号
InetAddress addr = address.getAddress();//返回InetAddress对象
System.out.println(addr.getHostName());//获取计算机名
System.out.println(addr.getHostAddress());//获取本地地址
}
}