InetAddress类|青训营笔记

141 阅读1分钟

InetAddress 类位于java.net包中,用于描述IP地址。它还有两个子类,分别是Inet4AddressInet6Address ,分别用来描述IPv4和IPv6 。由于InetAddress类没有public的构造方法,因此我们可以使用它的几个静态方法来创建实例。

// 最常使用
public static InetAddress getByName( String hostname );

// 返回多个实例,取决于本地DNS服务器的配置
public static InetAddress[] getAllByName( String hostname );

// 获取本机的地址
public static InetAddress getLocalHost();

使用以上方法需要保证网络通畅主机名称(域名)正确等条件;我们需要使用捕捉UnknownHostException异常。


对于一个InetAddress实例,我们有以下“Getters”:

// Getters

// 1. Returns the hostname you used to create the object.
public String getHostName();

// 2. Textual representation of the IP address (IPv4 or IPv6).
public String getHostAddress();

// 3. Returns the IP address as an array of 4 or 16 bytes.
public byte[] getAddress();

InetAddress实例是不可变对象,因此不存在公开的”Set“方法。


一些其他方法:

/**
 * Tests if the address is reachable.
 * Waits a maximum of timeOut milliseconds.
 * Similar to ping, but uses IP rather than ICMP.
 */
public boolean isReachable( int timeOut );

/**
 * Loopback addresses are returned as soon as they reach the Network layer.
 * Useful for testing without physical infrastructure.
 * IPv4: 127.*.*.*, usually 127.0.0.1
 * IPv6: 1, usually written ::1.
 */
public boolean isLoopBackAddress();

💡

InetAddress类的示例代码

  1. 实现Lookup类,使其与nslookup具有相同的功能
import java.net.*;

public class Lookup {
	private InetAddress inet = null; 
	public void resolve(String host) {
		try {
			inet = InetAddress.getByName(host); 
			System.out.println("Host name :" + inet.getHostName()); 
			System.out.println("IP Address:" + inet.getHostAddress());
		} catch( UnknownHostException e ) {
			e.printStackTrace(); 
		}
	}

	public static void main(String[] args) { 
		Lookup lookup = new Lookup(); 
		lookup.resolve(args[0]);
	} 
}