import java.net.*; /** * InetAddress Demo */ public class InetAddressDemo { public static void main(String[] args) { try { // 使用域名创建对象 InetAddress inetAd = InetAddress.getByName("www.yuncode.net");// getByName是InetAddress类的静态方法 System.out.println(inetAd); // 使用IP创建对象 InetAddress inetAd2 = InetAddress.getByName("127.0.0.1"); System.out.println(inetAd2); // 获得本机地址对象 InetAddress inetAd3 = InetAddress.getLocalHost(); System.out.println(inetAd3); // 获得对象中储存的域名 String host = inetAd3.getHostName(); System.out.println("域名: " + host); // 获得对象中储存的IP String ip = inetAd3.getHostAddress(); System.out.println("IP: " + ip); } catch (Exception e) { } } }