IP地址是网络中某个节点标识, 这个节点可能是计算机, 路由, 通讯设备. 下面这个Demo非常简单, 把它当作Java网络编程的起点.
import java.net.InetAddress; import java.net.UnknownHostException; public class Main { public static void main(String[] args) throws UnknownHostException { InetAddress addr = InetAddress.getLocalHost(); // 获得本机IP地址和主机名字 System.out.println(addr.getHostAddress()); System.out.println(addr.getHostName()); System.out.println("********************"); // 根据域名获得具体的IP地址 addr = InetAddress.getByName("www.baidu.com"); System.out.println(addr.getHostAddress()); System.out.println(addr.getHostName()); System.out.println("********************"); //addr = InetAddress.getByName("localhost"); addr = InetAddress.getByName("127.0.0.1"); System.out.println(addr.getHostAddress()); // 输出IP而不是域名。如果这个IP地址不存在或者DNS服务器不允许进行IP和域名映射, getHostName方法就直接返回这个IP System.out.println(addr.getHostName()); // 127.0.0.1 } }
