网络编程001
先学习三个基本对象,然后学习udp和tcp两种网络编程内容【详情在入门java—>网络编程梳理002、003】
UDP网络协议
TCP网络协议
IP对象
InetAddress : 表示IP地址
static InetAddress getLocalHost() 返回本地主机的地址。
String getHostAddress() 返回文本表示中的IP地址字符串。
String getHostName() 获取此IP地址的主机名。
static InetAddress getByName(String host) 根据主机名【/域名】称确定主机的IP地址。
public static void main(String[] args) throws UnknownHostException {
//static InetAddress getLocalHost() 返回本地主机的地址。
InetAddress ip1 = InetAddress.getLocalHost();
System.out.println(ip1); //主机名/IP地址
//String getHostAddress() 返回文本表示中的IP地址字符串。
//String getHostName() 获取此IP地址的主机名。
System.out.println(ip1.getHostAddress());
System.out.println(ip1.getHostName());
//static InetAddress getByName(String host) 根据主机名称确定主机的IP地址。
InetAddress ip2 = InetAddress.getByName("www.baidu.com");
System.out.println(ip2); //www.baidu.com/180.101.49.11
System.out.println(ip2.getHostAddress());
System.out.println(ip2.getHostName());
}
套接字InetSocketAddress
此类实现IP套接字地址(IP地址+端口号)它也可以是一对(主机名+端口号),在这种情况下,将尝试解析主机名
InetSocketAddress(String hostname, int port) —根据主机名和端口号创建套接字地址
InetSocketAddress(InetAddress addr, int port) --根据IP地址和端口号创建套接字地址
InetAddress getAddress() ----------------------------获取 InetAddress 。
String getHostName()--------------------------------- 获取 hostname 。
int getPort() -----------------------------------------------获取端口号。
public static void main(String[] args) {
//InetSocketAddress(String hostname,int port) 根据主机名和端口号创建套接字地址
//InetSocketAddress(InetAddress addr,int port) 根据IP地址和端口号创建套接字
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 9999);
System.out.println(inetSocketAddress);
//InenntAddress getAddress() 获取InetAddress
//String getHostName() 获取hostName
//int getPort() 获取端口
System.out.println(inetSocketAddress.getAddress().getHostName());
System.out.println(inetSocketAddress.getPort());
}
URL对象
类URL表示统一资源定位符,指向万维网上的“资源”的指针。
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://www.baidu.com:80/index.html?username=zhangsan&password=123#a");
System.out.println(url); // http://www.baidu.com:80/index.html?username=zhangsan&password=123#a
System.out.println(url.getProtocol()); // http
System.out.println(url.getHost()); // www.baidu.com
System.out.println(url.getPort()); // 80
System.out.println(url.getPath()); // /index.html
System.out.println(url.getFile()); // /index.html?username=zhangsan&password=123
System.out.println(url.getQuery()); // username=zhangsan&password=123
System.out.println(url.getRef()); // a
}