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的方法

Java 获取IP和机器名_第1张图片



你可能感兴趣的:(java)