網(wǎng)絡(luò)編程:Java獲取網(wǎng)絡(luò)主機信息

字號:

java.net.InetAddress類表示互聯(lián)網(wǎng)協(xié)議 (IP) 地址。
    有兩個子類:Inet4Address, Inet6Address
    通過 InetAddress可以方便獲取一個域名下的IP,也可以獲取一個IP的主機名。
    下面是例子,通過程序查看51cto主機的IP信息,51cto是不讓ping的。
    代碼:
    import java.io.IOException;
    import java.net.InetAddress;
    public class TestInetAddress {
    public static void main(String[] args) throws IOException {
    test();
    }
    public static void test() throws IOException {
    //獲取本機的IP地址
    InetAddress address1 = InetAddress.getLocalHost();
    System.out.println(address1.getHostAddress());
    System.out.println(address1.toString());
    System.out.println("---------------");
    //獲取51cot的IP地址
    InetAddress address2 = InetAddress.getByName("www.51cto.com");
    System.out.println("getHostAddress:\t" + address2.getHostAddress());
    System.out.println("getHostName:\t" + address2.getHostName());
    System.out.println("---------------");
    //獲取我博客的IP地址
    InetAddress address3 = InetAddress.getByName("lavasoft.blog.51cto.com");
    System.out.println("getHostAddress:\t" + address3.getHostAddress());
    System.out.println("getHostName:\t" + address3.getHostName());
    //直接用ip地址構(gòu)建
    System.out.println(InetAddress.getByName("211.103.156.224"));
    System.out.println("---------------");
    //獲取www.google.com域名下所有的IP地址
    //InetAddress[] address4 = InetAddress.getAllByName("www.microsoft.com");
    InetAddress[] address4 = InetAddress.getAllByName("www.google.com");
    for (InetAddress address : address4) {
    //System.out.println(address.getHostAddress());
    System.out.println(address);
    }
    InetAddress address5 = InetAddress.getByName("211.103.156.229");
    System.out.println(address5.isReachable(10));
    }
    }
    運行輸出結(jié)果:
    192.168.1.2
    lavasoft/192.168.1.2
    ---------------
    getHostAddress: 211.103.156.229
    getHostName: www.51cto.com
    ---------------
    getHostAddress: 211.103.156.224
    getHostName: lavasoft.blog.51cto.com
    /211.103.156.224
    ---------------
    www.google.com/64.233.189.99
    www.google.com/64.233.189.104
    www.google.com/64.233.189.147
    false
    Process finished with exit code 0