?? 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 + -