1,InetAddress类的使用
java.net.InetAddress类的主要作用是代表IP地址
InetAddress类没有提供构造方法,而是提供了两个静态方法来获取InetAddress实例
getByName(String host):根据主机获取对应的InetAddress对象
getByAddress(byte[] addr):根据原始IP地址来获取对应的InetAddress对象
InetAddress还提供了3个方法来获取InetAddress实例对应的IP地址和主机名
String getCanonicalHostName():获取次IP地址的完全限定域名
String getHostAddress():返回该InetAddress实例对应的IP地址(字符串形式)
String getHostName();获取此IP地址的主机名
获取本机IP的实例
import java.net.InetAddress;
public class TestNet1 {
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("192.168.13.17");//创建inetaddress类的实例
System.out.println("baidu是否可以到达"+ip.isReachable(2000));//判断能否到达inetaddress
System.out.println(ip.getHostAddress());
InetAddress local=InetAddress.getByAddress(new byte[]{127,0,0,1});
System.out.println("是否可以到达"+local.isReachable(2000));
System.out.println("获取限定域名"+local.getCanonicalHostName());
}catch(Exception e){
e.printStackTrace();
}
}
}
2,URL类的使用
URL可以由协议名、主机、端口和资源组成
URL的格式为"protocal://host:port/resourceName"
用以下方法可以调用URL对应的资源
String getFile():获取此URL的资源名
String getHost():获取此URL的主机名
String getPath():获取此URL的路径部分
int getport():获取此URL的端口号
URL类的简单用法
import java.net.MalformedURLException;
import java.net.URL;
public class TestNet2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
URL aURL;
try {
aURL = new URL("http://java.sun.com:80/docs/books/tutorial"+"/index.html?name=networking#DOWNLOADING");
System.out.println("protocol="+aURL.getProtocol());
System.out.println("authority="+aURL.getAuthority());
System.out.println("host="+aURL.getHost());
System.out.println("port="+aURL.getPort());
System.out.println("path="+aURL.getPath());
System.out.println("query="+aURL.getQuery());
System.out.println("filename="+aURL.getFile());
System.out.println("ref="+aURL.getRef());
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
通过URL来下载网页信息
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class TestNet3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
URL url=new URL("www.sina.com/");
InputStreamReader isr=new InputStreamReader(url.openStream());
BufferedReader in=new BufferedReader(isr);
String inputLine;
FileOutputStream fos=new FileOutputStream("d:\\mydownloadhtml.html");
while((inputLine=in.readLine())!=null){
fos.write(inputLine.getBytes());
}
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
}