作业帮 > JAVA > 教育资讯

Java教程:Java获取网络主机信息

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/08 13:49:11 JAVA
Java教程:Java获取网络主机信息
Java教程:Java获取网络主机信息JAVA
【无忧考网-Java教程:Java获取网络主机信息】:

    java.InetAddress类表示互联网协议 (IP) 地址。

    有两个子类:Inet4Address, Inet6Address

    通过 InetAddress可以方便获取一个域名下的IP,也可以获取一个IP的主机名。

    下面是例子,通过程序查看bitscn主机的IP信息,bitscn是不让ping的。

    代码:

import java.io.IOException; 
import java.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.bitscn"); 
                System.out.println("getHostAddress:\t" + address2.getHostAddress()); 
                System.out.println("getHostName:\t" + address2.getHostName()); 
                System.out.println("---------------"); 
                //获取我博客的IP地址 
                InetAddress address3 = InetAddress.getByName("lavasoft.blog.bitscn"); 
                System.out.println("getHostAddress:\t" + address3.getHostAddress()); 
                System.out.println("getHostName:\t" + address3.getHostName()); 
                //直接用ip地址构建 
                System.out.println(InetAddress.getByName("211.103.156.224")); 

                System.out.println("---------------"); 
                //获取www.google域名下所有的IP地址 
//                InetAddress[] address4 = InetAddress.getAllByName("www.microsoft"); 
                InetAddress[] address4 = InetAddress.getAllByName("www.google"); 
                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)); 
        } 
}

    运行输出结果:

192.168.1.2
lavasoft/192.168.1.2
---------------
getHostAddress:  211.103.156.229
getHostName:  www.bitscn
---------------
getHostAddress:  211.103.156.224
getHostName:  lavasoft.blog.bitscn
/211.103.156.224
---------------
www.google/64.233.189.99
www.google/64.233.189.104
www.google/64.233.189.147
false

Process finished with exit code 0


JAVA