获取IP地址和域名

import java.net.InetAddress;
import java.net.UnknownHostException;
/**
获取IP地址和域名
*/
public class GetIPAddress{
    //通过InetAddress静态方法获取本机网络地址信息,在通过InetAddress实例方法获取本机网路IP信息
    //host包括hostname/hostaddress
    public String getLocalIP() throws UnknownHostException{
        System.out.println("InetAddress-localhost: "+InetAddress.getLocalHost().toString());
        System.out.println("getLocalIP: "+InetAddress.getLocalHost().getHostAddress());
        return InetAddress.getLocalHost().getHostAddress();
        }
    //通过InetAddress实例方法获取本机的域名或者主机名
    public String getHostName() throws UnknownHostException{
        System.out.println("getHostName: "+InetAddress.getLocalHost().getHostName());
        return InetAddress.getLocalHost().getHostName();
        }
    //通过InetAddress静态方法通过域名获取网络信息(InetAddress)
    //getHostAddress()和getHostAddress()是相对的,如果没有指定参数则是相对于本机,如果指定参数就是相对于指定的参数
    public String getIPByName(String str) throws UnknownHostException{
        System.out.println("域名为"+str+"的IP: "+InetAddress.getByName(str).getHostAddress());
        return InetAddress.getByName(str).getHostAddress();
        }
    //通过InetAddress静态方法通过域名获取多IP本机网络信息(InetAddress)
    public String[] getAllIPByName(String str) throws UnknownHostException{
        System.out.println("域名为"+str+"的所有IP: ");
        int numIP = InetAddress.getAllByName(str).length;
        InetAddress[] inetAddress = InetAddress.getAllByName(str);
        String[] IPs = new String[numIP];
        for(int i=0;i<numIP;i++){
            String temp = inetAddress[i].getHostAddress();
            IPs[i] = temp;
            System.out.println("IP["+i+"]: "+temp);
            }
        return IPs;
        }
    public static void main(String[] args) throws UnknownHostException{
        GetIPAddress getIP = new GetIPAddress();
        getIP.getLocalIP();
        System.out.println("======================================================");
        getIP.getHostName();
        System.out.println("======================================================");
        getIP.getIPByName("www.google.cn");
        System.out.println("======================================================");
        getIP.getAllIPByName("www.google.cn");
        }
    }

编译执行结果:
G:\maul keyboard\network programming>javac GetIPAddress.java

G:\maul keyboard\network programming>java GetIPAddress
InetAddress-localhost: MS-20160816QAVW/10.0.216.208
getLocalIP: 10.0.216.208
======================================================
getHostName: MS-20160816QAVW
======================================================
域名为www.google.cn的IP: 203.208.40.127
======================================================
域名为www.google.cn的所有IP:
IP[0]: 203.208.40.127
IP[1]: 203.208.40.120
IP[2]: 203.208.40.111
IP[3]: 203.208.40.119

G:\maul keyboard\network programming>

猜你喜欢

转载自www.cnblogs.com/celine/p/9940067.html