JAVA編程取得IP地址

來源:互聯網
上載者:User

在TCP/IP 互連網時,經常會需要查詢自己主機的IP地址和www伺服器的IP地址。雖然,我們可以使用IPCONFIG 和PING 進行IP地址查詢,但是如果在應用程式或APPLET中使用此命令會破壞我們應用程式介面。

為此本人使用JAVA 做了一個簡單的程式可以直接查詢自己主機的IP地址和www伺服器的IP地址:

// 檔案名稱為 NetTool.java (注意:在JAVA 語言中大小寫敏感)

import java.net.*;
public class NetTool{
InetAddress myIPaddress=null;
InetAddress myServer=null;
public static void main( String args[]){
NetTool mytool;
mytool=new NetTool();
System.out.println("Your host IP is: "
+ mytool.getMyIP());
System.out.println("The Server IP is :"
+mytool.getServerIP());
}
//取得LOCALHOST的IP地址
public InetAddress getMyIP() {
try { myIPaddress=InetAddress.getLocalHost();}
catch (UnknownHostException e) {}
return (myIPaddress);
}
//取得 www.bianceng.cn 的IP地址
public InetAddress getServerIP(){
try {myServer=InetAddress.getByName(
"www.bianceng.cn");}
catch (UnknownHostException e) {}
return (myServer);
}
}

---- 由於JAVA語言的跨平台特性,以上程式編譯後可直接在任何裝有JVM系統的機器上運行。以上程式旨在拋磚引玉,讀者可將上述代碼稍加變換轉化成APPLET加到你的homepage中,或將地址查詢結果寫到一個檔案中去,建立自己本地的hosts檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.