Java InetAddress類的方法
阿新 • • 發佈:2021-12-22
本文為joshua317原創文章,轉載請註明:轉載自joshua317部落格https://www.joshua317.com/article/218
Java InetAddress類的方法
這個類表示網際網路協議(IP)地址。下面列出了 InetAddress 類常用的方法:
序號 | 方法描述 |
---|---|
1 | static InetAddress getByAddress(byte[] addr)在給定原始 IP 地址的情況下,返回 InetAddress 物件。 |
2 | static InetAddress getByAddress(String host, byte[] addr)根據提供的主機名和 IP 地址建立 InetAddress。 |
3 | static InetAddress getByName(String host)在給定主機名的情況下確定主機的 IP 地址。 |
4 | String getHostAddress()返回 IP 地址字串(以文字表現形式)。 |
5 | String getHostName()獲取此 IP 地址的主機名。 |
6 | static InetAddress getLocalHost()返回本地主機。 |
7 | String toString()將此 IP 地址轉換為 String。 |
package com.joshua317; import java.net.InetAddress; import java.net.UnknownHostException; public class Main { public static void main(String[] args){ InetAddressTest inetAddress = new InetAddressTest(); try { //根據域名獲取 InetAddress address1 = inetAddress.getInetAddress("www.baidu.com"); System.out.println(address1); System.out.println(address1.getHostName() + "--" +address1.getHostAddress()); //根據ip獲取 InetAddress address2 = inetAddress.getInetAddressByIp("103.235.46.39"); System.out.println(address2); System.out.println(address2.getHostName() + "--" +address2.getHostAddress()); //根據byte型別獲取 byte[] bytes = {103,34,46,39}; InetAddress address3 = inetAddress.getInetAddress(bytes); System.out.println(address3); //如果數值超出Byte最大範圍,需要進行轉換,例如:(byte)(235 &0xff) System.out.println("Byte最小值:" + Byte.MIN_VALUE); System.out.println("Byte最大值:" + Byte.MAX_VALUE); byte[] bytes2 = {103,(byte)(235 &0xff),46,39}; InetAddress address4 = inetAddress.getInetAddress(bytes2); System.out.println(address4); //檢視是否是迴環地址 InetAddress address5 = inetAddress.getInetAddressByIp("127.0.0.1"); System.out.println(address5.isLoopbackAddress()); //檢視是否是本地地址 System.out.println(address5.isLinkLocalAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } } @SuppressWarnings("all") class InetAddressTest { public InetAddressTest() { } public InetAddress getInetAddress(String host) throws UnknownHostException{ return InetAddress.getByName(host); } public InetAddress getInetAddress(byte[] host) throws UnknownHostException{ return InetAddress.getByAddress(host); } public InetAddress getInetAddress(String host,byte[] ipByte) throws UnknownHostException{ return InetAddress.getByAddress(host, ipByte); } public InetAddress getInetAddressByIp(String ip) throws UnknownHostException{ String[] ipStr = ip.split("\\."); byte[] ipByte = new byte[4]; for (int i =0; i<ipByte.length; i++) { ipByte[i] = (byte) (Integer.parseInt(ipStr[i]) &0xff); } return InetAddress.getByAddress(ipByte); } }
本文為joshua317原創文章,轉載請註明:轉載自joshua317部落格https://www.joshua317.com/article/218