1.获取本机的地址
package com.uwo9.test01;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Test01 {
public static void main(String[] args) {
InetAddress iAddress;
InetAddress iAddress2;
try {
// 获取本机的地址
iAddress = InetAddress.getLocalHost();
System.out.println("主机名:" + iAddress.getHostName());
System.out.println("字符串ip:" + iAddress.getHostAddress());
iAddress2 = InetAddress.getByName("www.baidu.com");
// 注意事项:有可能返回的主机ip有很多,只是显示了中的一个
System.out.println(iAddress2.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
2.获取局域网内所有的ip信息
package com.uwo9.test01;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* 获取局域网内所有的ip信息
* dos命令 arp -a
*
* java代码调用dos命令
* Process process = Runtime.getRuntime().exec("arp -a")
*
*/
public class Test03 {
public static void main(String[] args) {
// dos命令
String cmd = "arp -a";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String content = br.readLine();
while (content != null) {
System.out.println(content);
content = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}