Sockets编程——InetAddress类

来源:互联网 发布:免费域名注册网站 编辑:程序博客网 时间:2024/06/05 15:33

InetAddress类用于标识网络上的硬件资源,表示互联网协议(Ip地址)。

InetAddress没有构造方法,也就是说我们不能通过new 的方式创建一个InetAddress对象,但是我们可以通过提供的静态方法获取一个实例 getLocalHost() , getByAddress(byte add[])

InetAddress常用方法:

String getHostAddress() 返回IP地址字符串(以文本表现形式)

String getHostName()获取此IP地址的主机名

测试:

public static void main(String[] args) throws UnknownHostException {InetAddress address= InetAddress.getLocalHost();System.out.println("获取IP地址"+address.getHostAddress());System.out.println("计算机名:"+address.getHostName());byte[] bytes = address.getAddress();//获取字节数组形式的IP地址System.out.println("字节数组形式的IP:"+Arrays.toString(bytes));System.out.println(address);//根据主机名称获取InetAddress实例//InetAddress address2=InetAddress.getByName("txr");//根据IP地址来获取主机名InetAddress address2 = InetAddress.getByName("169.254.55.24");System.out.println("计算机名:"+address2.getHostName());System.out.println("IP地址:"+address2.getHostAddress());}


0 0