转载请注明出处:网络通信InetAddress、URL_Mr_Leixiansheng的博客-CSDN博客
主要介绍:InetAddress、URL
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;
public class SocketTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
inetAddressTest();
urlTest();
}
/**
* 获取网络资源
*/
private static void urlTest() {
// TODO Auto-generated method stub
try {
//创建一个URL实例
URL imooc = new URL("http://www.baidu.com");
//?后面表示参数 #后面表示锚点
URL url = new URL(imooc,"/index.html?username=tom#test");
System.out.println("协议:"+url.getProtocol());
System.out.println("主机:"+url.getHost());
//如果未指定端口号,则使用默认端口号
System.out.println("端口:"+url.getPort());
System.out.println("文件路径"+url.getPath());
System.out.println("文件名:"+url.getFile());
System.out.println("相对路径:"+url.getRef());
System.out.println("查询字符串:"+url.getQuery());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*获取硬件资源
*/
private static void inetAddressTest() {
// TODO Auto-generated method stub
InetAddress address;
try {
address = InetAddress.getLocalHost(); //获取本机地址
// address = InetAddress.getByName("本机计算机名"); //获取本机地址,通过名字
// address = InetAddress.getByName("本机IP"); //获取本机地址,通过IP
//输出本机计算机名
System.out.println("计算机名:"+address.getHostName());
//输出本机IP
System.out.println("ip:"+address.getHostAddress());
byte[] addByte = address.getAddress();
//byte范围在-128~127
System.out.println("字节形式数组IP:"+Arrays.toString(addByte));
//输出计算机名和IP
System.out.println(address);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}