InetAddress类
一.InetAddress类:
InetAdderss类是JDK中提供了一个类,该类用于封装一个IP地址,并提供了一系列与IP地址相关的方法。
二.常用方法:
常用方法 | |
---|---|
static InetAddress | getByName(String host)----在给定主机名的情况下确定主机的IP地址 |
static InetAddress | getLocalHost()----返回本地主机 |
String | getHostName()----获取此IP地址的主机名 |
String | getHostAddress()----返回IP地址字符串(以文本表现形式) |
上表中,列举了InetAddress的四个常用方法。其中,前两个方法用于获得该类的实例对象,第一个方法用于获得表示指定主机的InetAddress对象,第二个方法用于获得表示本地的InetAddress对象。通过InetAddress对象便可获取指定主机名,IP地址等,接下来通过一个案例来演示InetAddress的常用方法,如下所示。
三.代码实例:
1.在给定主机名的情况下确定主机的域名和IP地址:
import java.net.InetAddress;
public class Test {
public static void main(String[] args) throws Exception {
InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
System.out.println("该主机域名和IP地址:"+inetAddress);
}
}
2.获取本机的域名和IP地址:
import java.net.InetAddress;
public class Test {
public static void main(String[] args) throws Exception {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("本机的域名和IP地址"+localHost);
}
}
3.获取给定主机的主机名:
import java.net.InetAddress;
public class Test {
public static void main(String[] args) throws Exception {
InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
System.out.println("该主机域名:"+inetAddress.getHostName());
}
}
4.获取给定主机的IP地址:
import java.net.InetAddress;
public class Test {
public static void main(String[] args) throws Exception {
InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
//获取inetAddress对应的域名:
System.out.println("该主机名的IP地址为:"+inetAddress.getHostAddress());
}
}