InetAddress类的使用
package com.inetaddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Test;
/**
* InetAddress类的使用
* 1. 获取InetAddress类的方式:
* 1)getByName(String host):通过主机(IP地址)获取(掌握)
* 2)getLocalHost():获取本机的InetAddress对象(IP地址为127.0.0.1/localhost)
* 2. InetAddress类的方法使用:
* 1)getHostAddress():获取主机IP地址(掌握)
* 2)getHostName():获取主机名称(掌握)
*/
public class InetAddressTest {
@Test
public void test2() {
try {
InetAddress inet = InetAddress.getByName("www.baidu.com");
System.out.println(inet);
String host = inet.getHostAddress();
System.out.println(host);
String name = inet.getHostName();
System.out.println(name);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@Test
public void test() throws Exception {
InetAddress addr1 = InetAddress.getByName("192.168.10.1");
System.out.println(addr1);
InetAddress addr2 = InetAddress.getByName("www.baidu.com");
System.out.println(addr2);
//InetAddress addr3 = InetAddress.getByName("127.0.0.1");
InetAddress addr3 = InetAddress.getByName("localhost");
System.out.println(addr3);
InetAddress addr4 = InetAddress.getLocalHost();
System.out.println(addr4);
/*
// 下面两种不常用
byte[] addr = {89,57,21,7};
InetAddress addr2 = InetAddress.getByAddress(addr);
System.out.println(addr2);
//InetAddress addr3 = InetAddress.getByAddress("localhost", "127.0.0.1".getBytes());
//System.out.println(addr3);
*/
}
}