📄 hostlookup.java
字号:
import java.net.*;
import java.io.*;
public class HostLookup {
public static void main (String[] args) {
if (args.length > 0) { // 使用命令行的方式
for (int i = 0; i < args.length; i++) {
System.out.println(lookup(args[i]));
}
}
else {
//使用BufferedReader类来装饰输入流
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println(
"Enter names and IP addresses. Enter \"exit\" to quit.");
try {
while (true) {
String host = in.readLine( );
if (host.equals("exit")) break;
System.out.println(lookup(host));
}
}
catch (IOException e) {
System.err.println(e);
}
}
} /*main的结尾*/
private static String lookup(String host) {
InetAddress thisComputer;
byte[] address;
// 获得IP地址的类型
try {
thisComputer = InetAddress.getByName(host);
address = thisComputer.getAddress( );
}
catch (UnknownHostException e) {
//返回一个字符串
return "Cannot find host " + host;
}
if (isHostName(host)) {
// 打印IP地址
String dottedQuad = "";
for (int i = 0; i < address.length; i++) {
int unsignedByte = address[i] < 0 ? address[i] + 256 :
address[i];
dottedQuad += unsignedByte;
if (i != address.length-1) dottedQuad += ".";
}
return dottedQuad;
}
else { // 这是IP地址
return thisComputer.getHostName( );
}
} //lookup的结尾
private static boolean isHostName(String host) {
char[] ca = host.toCharArray( );
//当字符不是数字或句号
// 这是一个主机名字
for (int i = 0; i < ca.length; i++) {
if (!Character.isDigit(ca[i])) {
if (ca[i] != '.') return true;
}
}
// 所有的是数字或句号
// 所以主机名字像IP地址一样
return false;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -