1. 程式人生 > >Java 獲取IP和機器名

Java 獲取IP和機器名

1. 通過IP獲取機器名 or 通過機器名獲取ip

    host :主機       hostAddress :ip       hostName:機器名

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Test01 {
    public static void main(String[] args) throws UnknownHostException {  
        InetAddress addr=null;  
        String ip="";  
        String address="";  
        try{  
            // cp01-fengchao-public-7.epc.baidu.com|10.95.130.73
            addr = InetAddress.getByName("cp01-fengchao-public-7.epc.baidu.com");
            ip = addr.getHostAddress().toString(); //獲得機器IP    
            address = addr.getHostName().toString(); //獲得機器名稱  
            System.out.println(ip + "|" + address);
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }    
}
2. 獲取本機的ip和機器名
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Test01 {
    public static void main(String[] args) throws UnknownHostException {  
        InetAddress addr=null;  
        String ip="";  
        String address="";  
        try{  
            // cp01-fengchao-public-7.epc.baidu.com|10.95.130.73
//            addr = InetAddress.getByName("cp01-fengchao-public-7.epc.baidu.com");
            addr = InetAddress.getLocalHost();
            ip = addr.getHostAddress().toString(); //獲得機器IP    
            address = addr.getHostName().toString(); //獲得機器名稱  
            System.out.println(ip + "|" + address);
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }    
}
3. java.net.InetAddress的方法