通信的要素——IP :
InetAddress类介绍:
代码示例:
/* * 网络通信的第一要素:IP地址。通过IP地址,唯一地定位互联网上一台主机 * InetAddress:位于java.net包下 * 1.InetAddress用来代表IP地址。一个InetAddress的对象就代表这一个IP地址 * 2,如何创建InetAddress的对象:getByName(String host) * 3.getHostName():获取IP地址对应的域名 * getHostAddress():获取IP地址 * */ public class TestInetAddress { public static void main(String[] args) throws Exception { InetAddress inet = InetAddress.getByName("www.baidu.com"); // inet = InetAddress.getByName("14.215.177.39"); System.out.println(inet); //两个方法 System.out.println(inet.getHostName()); System.out.println(inet.getHostAddress()); //获取本机的IP:getLocalHost() InetAddress inet1 = InetAddress.getLocalHost(); System.out.println(inet1.getHostName()); System.out.println(inet1.getHostAddress()); } }
结果:
www.baidu.com/14.215.177.39
www.baidu.com
下面打印结果涉及个人隐私不显示