Java網路程式設計之獲取IP地址:InetAddress類
阿新 • • 發佈:2019-02-05
示例程式碼:
/* * 網路通訊的第一個要素: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()); } }