熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java獲取網絡主機信息

2013-11-23 19:18:44  來源: Java核心技術 

  InetAddress類表示互聯網協議 (IP) 地址

  有兩個子類InetAddress InetAddress

  通過 InetAddress可以方便獲取一個域名下的IP也可以獲取一個IP的主機名

  下面是例子通過程序查看cto主機的IP信息cto是不讓ping的

  代碼

   import javaioIOException;
import InetAddress;

public class TestInetAddress {
        public static void main(String[] args) throws IOException {
                test();
        }

        public static void test() throws IOException {
                //獲取本機的IP地址
                InetAddress address = InetAddressgetLocalHost();
                Systemoutprintln(addressgetHostAddress());
                Systemoutprintln(addresstoString());

                Systemoutprintln();
                //獲取cot的IP地址
                InetAddress address = InetAddressgetByName();
                Systemoutprintln(getHostAddress:\t + addressgetHostAddress());
                Systemoutprintln(getHostName:\t + addressgetHostName());
                Systemoutprintln();
                //獲取我博客的IP地址
                InetAddress address = InetAddressgetByName(lav);
                Systemoutprintln(getHostAddress:\t + addressgetHostAddress());
                Systemoutprintln(getHostName:\t + addressgetHostName());
                //直接用ip地址構建
                Systemoutprintln(InetAddressgetByName());

                Systemoutprintln();
                //獲取域名下所有的IP地址
//                InetAddress[] address = InetAddressgetAllByName();
                InetAddress[] address = InetAddressgetAllByName();
                for (InetAddress address : address) {
//                                Systemoutprintln(addressgetHostAddress());
                        Systemoutprintln(address);
                }

                InetAddress address = InetAddressgetByName();
                Systemoutprintln(addressisReachable());
        }
}

  運行輸出結果

  
lavasoft/

getHostAddress: 
getHostName: 

getHostAddress: 
getHostName:  lav
/

/
/
/
false

  Process finished with exit code


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26639.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.