IP地址了解
基本概念:
IP地址(Internet Protocol Address)是指互联网协议地址,又译为网络协议地址。IP地址是IP协议提供的一种统一的地址格式,它为互联网上的每一个网络和每一台主机分配一个逻辑地址,以此来屏蔽物理地址的差异。
这里主要是讲述关于Java编程的IP地址如何去获取,所以,对IP地址的关于计算机网络的知识不再详细描述,我们知道目前来说IPV4已经消耗殆尽,真正解决IP地址不够的办法其实就是使用IPV6,当然也可以通过网路地址转换来节省IP地址的消耗。
IP地址在Java中的运用
Java中表示获取IP地址的类是InetAddress,本机的IP地址是127.0.0.1或者叫localhost,至于域名的出现就是为了解决IP地址记忆的问题
关于InetAddress的Java代码测试
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 测试InetAddress类
*
* @author 87682
*/
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
InetAddress inetAddress3 = InetAddress.getByName("localhost");
System.out.println(inetAddress3);
InetAddress inetAddress4 = InetAddress.getLocalHost();
System.out.println(inetAddress4);
//查询网站地址
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
//常用方法
System.out.println(inetAddress2.getAddress());
System.out.println(inetAddress2.getCanonicalHostName());
System.out.println(inetAddress2.getHostAddress());
System.out.println(inetAddress2.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}