示例代码:
/*
* 网络通信的第一个要素:IP地址。通过IP地址,唯一的定位互联网上一台主机
* InetAddress:位于java.net包下
* 1.InetAddress用来代表IP地址。一个InetAdress的对象就代表着一个IP地址
* 2.如何创建InetAddress的对象:getByName(String host)
* 3.getHostName(): 获取IP地址对应的域名
* getHostAddress():获取IP地址
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Test;
public class TestInetAddress {
@Test
public void testInetAddress() throws UnknownHostException {
InetAddress inet = InetAddress.getByName("www.jmu.edu.cn");
//inet = InetAddress.getByName("210.34.128.132");
System.out.println(inet);//www.jmu.edu.cn/210.34.128.132
System.out.println(inet.getHostName());//www.jmu.edu.cn
System.out.println(inet.getHostAddress());//210.34.128.132
//获取本机的IP
inet = InetAddress.getLocalHost();
System.out.println(inet);
System.out.println(inet.getHostName());
System.out.println(inet.getHostAddress());
}
}