IP测试类:
InetAddress 测试:
package ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
/**
* java 中提供的两个类
* InetAddress 获取ip 能获取端口?不能
* InetSocketAddress 获取ip 和端口
* @author superdrew
*/
public class TestInetAddress {
public static void main(String[] args) throws UnknownHostException {
//获取本机的ip地址和域名
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia.toString());
System.out.println(ia.getHostName());//域名 127
System.out.println(ia.getHostAddress());//ip地址 192.168.201.254
System.out.println(Arrays.toString(ia.getAddress()));//-64, -88, 6, -2(最高位是1)
//获取固定网址的ip和域名
InetAddress ia2 = InetAddress.getByName("www.baidu.com");
System.out.println(ia2.toString());
System.out.println(ia2.getHostName());//域名 127
System.out.println(ia2.getHostAddress());//ip地址
}
}
结果展示:
IntSocketAddress.java测试类:
package ip;
import java.net.InetSocketAddress;
/**
* InetSocketAddress 获取ip和端口的
* @author superdrew
*
*/
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress is = new InetSocketAddress("www.baidu.com", 1234);
System.out.println(is.getHostName()); //获取域名
System.out.println(is.getPort()); //获取端口
System.out.println(is.getAddress()); //返回是一个InetAddress对象
}
}
结果展示:
测试TestURL.java类:
package ip;
import java.net.MalformedURLException;
import java.net.URL;
/**
* URL
* @author superdrew
*
*/
public class TestURL {
public static void main(String[] args) throws MalformedURLException {
URL u = new URL("https://www.baidu.com:8080/index.html?username=superdrew");
/*System.out.println("获取与此url关联的协议的默认端口:"+u.getDefaultPort());
System.out.println("getFile:"+u.getFile()); //端口号后面的内容
System.out.println("主机名:"+u.getHost()); //www.google.cn
System.out.println("路径:"+u.getPath()); //端口号后,参数前的内容
System.out.println("端口:"+u.getPort()); //存在返回80.否则返回-1
System.out.println("协议:"+u.getProtocol());
System.out.println("参数部分:"+u.getQuery());
System.out.println("锚点:"+u.getRef()); */
System.out.println(u.getHost()); //获取域名
System.out.println(u.getPort()); //端口
System.out.println(u.getProtocol()); //协议
System.out.println(u.getFile()); //路径
System.out.println(u.getPath()); //路径
//System.out.println(u.getRef()); //获取锚点,#后面的 定位的
System.out.println(u.getQuery()); //获取路径内的参数内容
URL u2 = new URL("http://www.abc.com/aa/");
URL u3 = new URL(u2,"text.html"); //相对路径构建url对象 往后追加
System.out.println(u3.toString()); //http://www.abc.com/aa/2.html
}
}
结果展示: