Java Web --- 域名 IP 端口的封装类

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());//获取本地地址
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值