1. 程式人生 > >獲取IP地址和域名

獲取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>