一、InetAddress类
作用:封装计算机的IP地址,不包含端口号
常用方法:1)String getHostAddress() --->获得IP地址
2)String getHostName()---->获得主机名
3)static InetAddress getByName(String host) --->根据主 机名获得IP地址
public class TestInetAddress {
public static void main(String[] args) throws UnknownHostException {
//(1)获取InetAddress的方式
InetAddress ia = InetAddress.getLocalHost();//返回本地主机的地址。
System.out.println(ia);
System.out.println("获取主机ip地址:"+ia.getHostAddress());//返回文本表示中的IP地址字符串。
System.out.println("获取主机名称:"+ia.getHostName());//获取此IP地址的主机名。
//(2)根据域名得到InetAddress对象
InetAddress ia2=InetAddress.getByName("www.jd.com");
System.out.println("京东服务器的IP地址:"+ia2.getHostAddress());
System.out.println("主机名称:"+ia2.getHostName());
//(3)根据IP地址获得一个InetAddress对象
InetAddress ia3=InetAddress.getByName("192.168.41.26");
System.out.println(ia3.getHostAddress());
System.out.println(ia3.getHostName());
}
}
二、InetSocketAddress类
作用:用于实现IP套接字地址(IP地址+端口号),用于socket通信
常用方法:1)InetAddress / getAddress() --->获取获取InetAddress 对象
2)int getPort()---->获取端口号
3)String getHostName() ----> 获取主机名
public class TestInetSocketAddress {
public static void main(String[] args) throws UnknownHostException {
InetSocketAddress isa=new InetSocketAddress("localhost", 8888);
InetSocketAddress isa2=new InetSocketAddress("192.168.42.12", 9999);
InetSocketAddress isa3=new InetSocketAddress("127.0.0.1",7777);
InetAddress ia=InetAddress.getByName("192.168.41.26");//("localhost");
InetSocketAddress isa4=new InetSocketAddress(ia, 9999);
System.out.println("主机名称:"+isa4.getHostName());
System.out.println("主机IP地址:"+isa4.getAddress());
}
}
三、URL类
定义:统一资源定位符,由4部分组成:协议、存放资源的主机域名、端口号和资源文件名。
如https:// www.buidu.com: 80/ index.html#aa?
协议 主机域名 端口号 资源文件名
URL是指向互联网“资源”的指针
资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。
常用方法:
- String getProtocal() 获取此URL的协议名称
- String getHost() 获取此URL的主机名(如果适用)
- int getPort() 获取URL的端口号
- String getFile() 获取此URL的文件名
- getDefaultPort() 获取与此URL关联协议的默认端口号
- getPath() 获取此URL的路径部分
- openStream()——打开到此URL的连接并返回一个用于从该连接读入的 InputStream
public class TestURL {
public static void main(String[] args) throws MalformedURLException {
URL u=new URL("http://www.itbaizhan.cn/course/id/216.html");
System.out.println("获取协议:"+u.getProtocol());
System.out.println("获取此URL的主机名:"+u.getHost());
System.out.println("获取端口号:"+u.getPort());//如果没写则返回-1
System.out.println("获取此URL的文件名:"+u.getFile());
System.out.println("获取资源路径:"+u.getPath());
System.out.println("获取与此URL关联协议的默认端口号:"+u.getDefaultPort());
}
}
/**
* 从网络上获取资源
*/
public class TestURL2 {
public static void main(String[] args) throws IOException {
URL u=new URL("http://www.baidu.com");
InputStream is = u.openStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is,"utf-8"));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("save.html"),"utf-8"));
String line=null;
while((line=br.readLine())!=null) {
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
}