Java gets the local host name and IP address

Java gets the local host name and IP address

1. Knowledge explanation

1. Get the InetAddress class

(1) Obtain information about the local computer

InetAddress i = InetAddress.getLocalHost();

(2) Obtain computer-related information through the computer name
Among them, the parameter host in the method can be the host alias or the host IP. Example: "Person-PC", "www.126.com", "10.0.70.30", "220.181.72.180"

String host = "Person-PC";
InetAddress i = InetAddress.getByName(host);

2. Get the host name

(1) Get the host alias

String hostName = i.getHostName();

(2) Obtain the host name (sometimes the host name is the same as the host alias, and sometimes the host name is the same as the host IP)

String canonicalHostName = i.getCanonicalHostName();

3. Obtain the host IP

(1) Obtain the host IP (IP address in the form of a string)

String address = i.getHostAddress();

(2) Obtain the host IP (IP address in the form of byte array)

byte[] address = i.getAddress();

2. Application cases

    public static void main(String[] args) {
    
    
        try {
    
    
            String[] hosts = {
    
    "Person-PC", "www.126.com", "10.0.70.30", "220.181.72.180"};
            for (String host : hosts) {
    
    
                // 获取 InetAddress 类
                InetAddress i = InetAddress.getByName(host); // 通过计算机名称获取计算机相关信息
                // 获取主机名
                String hostName = i.getHostName(); // 获取主机别名,如:Person-PC
                String canonicalHostName = i.getCanonicalHostName(); // 获取主机名(有时出现主机名与主机别名相同,有时出现主机名与主机IP相同),如:Person-PC
                // 获取主机IP
                String hostAddress = i.getHostAddress(); //获取主机IP(字符串形式的IP地址),如: 10.0.70.30
                byte[] address = i.getAddress(); //获取主机IP(byte数组形式的IP地址),如:[B@78308db1

                // 打印
                System.out.println("host:" + host);
                System.out.println("主机别名:" + hostName);
                System.out.println("主机名:" + canonicalHostName);
                System.out.println("主机IP(字符串形式):" + hostAddress);
                System.out.println("主机名(byte数组形式):" + address);
                System.out.println();
            }
        } catch (UnknownHostException e) {
    
    
            e.printStackTrace();
        }
    }

Output result:

host:Person-PC
主机别名:Person-PC
主机名:Person-PC
主机IP(字符串形式):10.0.70.30
主机名(byte数组形式):[B@78308db1

host:www.126.com
主机别名:www.126.com
主机名:220.181.72.180
主机IP(字符串形式):220.181.72.180
主机名(byte数组形式):[B@27c170f0

host:10.0.70.30
主机别名:Person-PC
主机名:Person-PC
主机IP(字符串形式):10.0.70.30
主机名(byte数组形式):[B@5451c3a8

host:220.181.72.180
主机别名:220.181.72.180
主机名:220.181.72.180
主机IP(字符串形式):220.181.72.180
主机名(byte数组形式):[B@2626b418

Guess you like

Origin blog.csdn.net/Shipley_Leo/article/details/131024969