一、概念:
二、重要方法
1、InetAddress :封装IP及DNS
方法:
getHostAddress()
getHostName()
InetAddress.getLocalHost();
InetAddress.getByName("www.baidu.com");
2、InetSocketAddress :封装端口
1)创建对象
InetSocketAddress(String hostname,int port);
InetSocketAddress("localhost",9955);
2)方法
getAddress()
getHostName()
getPort()
代码示例
package cn.net; import java.net.InetAddress; import java.net.UnknownHostException; public class InetDemo01 { public static void main(String[] args) throws UnknownHostException { //使用getLocalHost方法创建InetAddress对象 InetAddress addr=InetAddress.getLocalHost(); System.out.println(addr.getHostAddress()); //返回 IP System.out.println(addr.getHostName()); //输出计算机名 //根据域名得到InetAddress对象 addr=InetAddress.getByName("www.baidu.com"); System.out.println(addr.getHostAddress()); //返回百度服务器的ip :39.156.66.18 System.out.println(addr.getHostName()); //输出www.baidu.com //根据ip得到InetAddress对象 addr=InetAddress.getByName("39.156.66.18"); System.out.println(addr.getHostAddress()); System.out.println(addr.getHostName()); } }
效果
InetSocketAddress 截个图吧
效果