InetAddress对域名进行解析是使用本地机器配置或者网络命名服务(如域名系统(Domain Name System,DNS)和网络信息服务(Network Information Service,NIS))来实现。

代码如下:

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

public class IPDomainHelper {

	private static String domainName="www.baidu.com";
	
	private static InetAddress ipAddress=null; 
	
	
	/**
	 * 根据域名解析IP地址
	 * @return
	 */
	public static String getServerIP()
	{
		String serverIp=null;
		try 
		{
			ipAddress=InetAddress.getByName(domainName);
			
			serverIp=ipAddress.getHostAddress();
		
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
			System.out.println("域名解析失败");
		}
		return serverIp;
	}
	
	/**
	 * 获得本地IP地址
	 * @return
	 */
	public static String getLocalHostIP()
	{
		String localIp=null;
		try 
		{
			ipAddress=InetAddress.getLocalHost();
			
			localIp=ipAddress.getHostAddress();
		
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
			System.out.println("域名解析失败");
		}
		return localIp;
	}
}



结束...