大家好,又见面了,我是你们的朋友全栈君。
InetAddress类的使用
package com.inetaddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Test;
/** * InetAddress类的使用 * 1. 获取InetAddress类的方式: * 1)getByName(String host):通过主机(IP地址)获取(掌握) * 2)getLocalHost():获取本机的InetAddress对象(IP地址为127.0.0.1/localhost) * 2. InetAddress类的方法使用: * 1)getHostAddress():获取主机IP地址(掌握) * 2)getHostName():获取主机名称(掌握) */
public class InetAddressTest {
@Test
public void test2() {
try {
InetAddress inet = InetAddress.getByName("www.baidu.com");
System.out.println(inet);
String host = inet.getHostAddress();
System.out.println(host);
String name = inet.getHostName();
System.out.println(name);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@Test
public void test() throws Exception {
InetAddress addr1 = InetAddress.getByName("192.168.10.1");
System.out.println(addr1);
InetAddress addr2 = InetAddress.getByName("www.baidu.com");
System.out.println(addr2);
//InetAddress addr3 = InetAddress.getByName("127.0.0.1");
InetAddress addr3 = InetAddress.getByName("localhost");
System.out.println(addr3);
InetAddress addr4 = InetAddress.getLocalHost();
System.out.println(addr4);
/* // 下面两种不常用 byte[] addr = {89,57,21,7}; InetAddress addr2 = InetAddress.getByAddress(addr); System.out.println(addr2); //InetAddress addr3 = InetAddress.getByAddress("localhost", "127.0.0.1".getBytes()); //System.out.println(addr3); */
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/152258.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...