更新時間:2022-05-12 11:08:25 來源:動力節(jié)點 瀏覽1331次
在這個例子中,我們將看到如何獲取系統(tǒng)的 IP 地址。步驟如下:
getLocalHost()
1.通過調(diào)用InetAddress 類的方法獲取本地主機地址。
2.通過調(diào)用getHostAddress()方法獲取IP地址。
導入java 。凈。網(wǎng)絡地址;
類GetMyIPAddress { public static void main ( String args []) throws Exception { /* public static InetAddress getLocalHost()
* throws UnknownHostException: 返回地址
* 本地主機。這是通過檢索來實現(xiàn)的
* 來自系統(tǒng)的主機名,然后解析
* 將該名稱轉(zhuǎn)換為 InetAddress。注:已解決
* 地址可能會被緩存一小段時間。
*/ InetAddress myIP = InetAddress 。獲取本地主機();
/* public String getHostAddress(): 返回 IP
* 文本顯示中的地址字符串。
*/系統(tǒng)。出來。println ( "我的IP地址是:" ); 系統(tǒng)。出來。println ( myIP.getHostAddress ( )) ; } }
輸出:
我的IP地址是:115.242 。7.243