Java网络编程InetAddress类

InetAddress用来代表IP地址。一个InetAdress的对象就代表着一个IP地址,

  • getByName(String host):在给定主机名的情况下确定主机的 IP 地址,主机名可以是机器名(如 "java.sun.com"),也可以是其 IP 地址的文本表示形式。如果提供字面值 IP 地址,则仅检查地址格式的有效性
  • getHostName(): 获取此 IP 地址的主机名
  • getHostAddress():返回 IP 地址字符串(以文本表现形式)
  • getLocalHost(): 返回本地主机

InetAddress对象的获取

     InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取:

  • static InetAddress[] getAllByName(String host)
  • static InetAddress getByAddress(byte[] addr)
  • static InetAddress getByAddress(String host,byte[] addr)
  • static InetAddress getByName(String host)
  • static InetAddress getLocalHost()

注意:在这些静态方法中,最为常用的应该是getByName(String host)方法,只需要传入目标主机的名字,InetAddress会尝试做连接DNS服务器,并且获取IP地址的操作

package com.yyx.test;

import java.net.InetAddress;

public class TestInetAddress {
    public static void main(String[] args) {
        InetAddress inetAddress = null;
        InetAddress iAddress=null;
        try {
            inetAddress = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress);
            System.out.println(inetAddress.getHostAddress());
            System.out.println(inetAddress.getHostName());
            
            System.out.println("=============================");
            iAddress=InetAddress.getLocalHost();
            System.out.println(iAddress);
            System.out.println(iAddress.getHostAddress());
            System.out.println(iAddress.getHostName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
运行结果:

www.baidu.com/61.135.169.125
61.135.169.125
www.baidu.com
=============================
DESKTOP-F4P6SPK/192.168.1.107
192.168.1.107
DESKTOP-F4P6SPK

猜你喜欢

转载自www.cnblogs.com/xianya/p/9216966.html