IP地址是Internet主机的作为路由寻址用的数字型标识,人不容易记忆。因而产生了域名(domain name)这一种字符型标识。DNS即为域名解析服务。在这里我们如果想通过java程序来解析域名获得真实IP的话,可以通过java的InetAddress类来实现。
import java.net.InetAddress; import java.net.UnknownHostException; /** * Description: * Author: * Date: 2019/10/21 */ public class Test01 { public static void main(String[] args) throws UnknownHostException { //获取本机IP地址 System.out.println("本机IP地址:"+ InetAddress.getLocalHost().getHostAddress()); //获取百度IP地址 System.out.println("www.baidu.com的地址:"+InetAddress.getByName("www.baidu.com").getHostAddress()); } }执行结果如下:
本机IP地址:10.48.11.179 www.baidu.com的地址:180.101.49.12 Process finished with exit code 0封装成方法:
public class InetAddressUtil { private static final Logger LOGGER = LoggerFactory.getLogger(InetAddressUtil.class); private InetAddressUtil() { } /** * * 功能描述: <br> * 〈获取IP地址〉 * * @return * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static String getIPAddress(){ String ip = null; try { InetAddress address = InetAddress.getLocalHost(); ip = address.getHostAddress(); } catch (Exception e) { LOGGER.error("getIPAddress end with error: {}.", ExceptionUtils.getStackTrace(e)); } return ip; } }