📜  Java InetAddress类

📅  最后修改于: 2020-09-28 03:12:17             🧑  作者: Mango

Java InetAddress类

Java InetAddress类表示IP地址。 java.net.InetAddress类提供了获取任何主机名IP的方法,例如www.javatpoint.com,www.google.com,www.facebook.com等。

IP地址由32位或128位无符号数字表示。 InetAddress的实例代表IP地址及其相应的主机名。地址类型有两种:单播和多播。单播是单个接口的标识符,而组播是一组接口的标识符。

此外,InetAddress具有缓存机制,用于存储成功和失败的主机名解析。

InetAddress类的常用方法

Method Description
public static InetAddress getByName(String host) throws UnknownHostException it returns the instance of InetAddress containing LocalHost IP and name.
public static InetAddress getLocalHost() throws UnknownHostException it returns the instance of InetAdddress containing local host name and address.
public String getHostName() it returns the host name of the IP address.
public String getHostAddress() it returns the IP address in string format.

Java InetAddress类的示例

让我们看一个简单的InetAddress类示例,以获取www.javatpoint.com网站的IP地址。

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

输出:

Host Name: www.javatpoint.com
IP Address: 206.51.231.148