Use java to get ip and host name | LSABLOG

首页 » Program » Java » 正文

Use java to get ip and host name

java.net.* is very useful,this program I use InetAddress to get local ip,host name,baidu ip and baidu’s host name.

import java.net.*;

public class Localip
{
    public static void main(String[] args) 
    {
        try 
        {
            InetAddress address = InetAddress.getLocalHost();
            InetAddress baidu = InetAddress.getByName("www.baidu.com");
            System.out.println (address);
            System.out.println (baidu);
            System.out.println ("Host Name:" + address.getHostName());
            System.out.println ("IP Address:" + address.getHostAddress());
            System.out.println ("baidu host name:" + baidu.getHostName());
        }
        catch (UnknownHostException e) 
        {
            System.out.println("Could not find local address!");
        }
    }
}

Comment