java 獲取本地路由器分配給電腦的IP地址與主機名相關
阿新 • • 發佈:2019-01-28
本人最近做PC端專案,遇到一個ip地址相關通訊方面的問題,經過網上資料的一些查詢覺得目前此方法相對較好,特在此做個記錄,各位路過的大神,如有更好的方法,麻煩留下解答,讓小弟借鑑下.
下面進入正題,首先獲取到本機的ip地址,比較簡單(主要通過cmd指令arp -a拿到當前電腦所有的快取地址與ip地址所對應表),如下程式碼
public class GoodWindowsExec {
@SuppressWarnings("unused")
public static ArrayList<String> exec(String cmdLine) {
ArrayList<String> lines = new ArrayList<>();
try {
String osName = System.getProperty("os.name");
String[] cmd = new String[3];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = cmdLine;
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
InputStreamReader ir = new InputStreamReader(proc.getInputStream(),"gbk");
LineNumberReader input = new LineNumberReader(ir);
String line = null;
while ((line = input.readLine()) != null){
System.out.println(line);
lines.add(line);
}
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
return lines;
}
public static void main(String args[]) {
exec("arp -a");
Enumeration<NetworkInterface> nets = NetworkInterface
.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
if (null != netint.getHardwareAddress()) {
List<InterfaceAddress> list = netint.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : list) {
String localip=interfaceAddress.getAddress().toString();
System.out.println("======="+localip+"===========");
}
}
}
因為我這邊的PC客戶端需要知道下位機目前的ip地址,而我只知道下位機的主機名,所以我通過得到本機的ip地址,然後遍歷ping出局域網下所能Ping通的ip地址然後放入集合中,在遍歷出這些地址所對應的主機名匹配,程式碼如下:
public class IP {
static public HashMap<String,String> ping; // ping 後的結果集
static ArrayList<String> actives = new ArrayList<>();
public HashMap<String,String> getPing() { // 用來得到ping後的結果集
return ping;
}
public static long begin;
// 當前執行緒的數量, 防止過多執行緒摧毀電腦
static int threadCount = 0;
public IP() {
ping = new HashMap<String,String> ();
}
public void Ping(String ip) throws Exception {
// 最多30個執行緒
while (threadCount > 30)
Thread.sleep(50);
threadCount += 1;
PingIp p = new PingIp(ip);
p.start();
}
public void PingAll() throws Exception {
// 首先得到本機的IP,得到網段
String localip = ListNets.getAllLocalIp().get(0).substring(1,ListNets.getAllLocalIp().get(0).length());
int k = 0;
k = localip.lastIndexOf(".");
String ss = localip.substring(0, k + 1);
Controller.IP3 = ss;
for (int i = 1; i <= 255; i++) { // 對所有區域網Ip
String iip = Controller.IP3 + i;
Ping(iip);
}
}
class PingIp extends Thread {
public String ip; // IP
public PingIp(String ip) {
this.ip = ip;
}
public void run() {
try {
Process p = Runtime.getRuntime().exec("ping " + ip + " -w 300 -n 1");
InputStreamReader ir = new InputStreamReader(p.getInputStream(),"gbk");
LineNumberReader input = new LineNumberReader(ir);
// 讀取結果行
for (int i = 1; i < 7; i++){
input.readLine();
}
String line = input.readLine();
if (line == null || line.length() < 17 || line.substring(8, 17).equals("timed out"))
ping.put(ip, "None");
else
actives.add(ip);
// 執行緒結束
threadCount -= 1;
} catch (IOException e) {
}
}
}
public ArrayList<String> getCrIP() throws Exception {
PingAll();
ArrayList<String> crip;
crip = actives;
return crip;
}
public class ConnectThread extends Thread{
@Override
public void run() {
IP ip = new IP();
ArrayList<String> lines =new ArrayList<>();
try {
lines = ip.getCrIP();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<String> ips = new ArrayList<>();
for(String line:lines){
try {
String localip = ListNets.getAllLocalIp().get(0).substring(1,ListNets.getAllLocalIp().get(0).length());
int k = 0;
k = localip.lastIndexOf(".");
String ss = localip.substring(0, k + 1);
Controller.IP3 = ss;
if(line.indexOf(Controller.IP3) ==0){
String[] s = line.trim().split(" ");
ips.add(s[0].trim());
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0;i<ips.size();i++){
byte[] address=toIpByte(ips.get(i));
InetAddress addr;
try {
addr = InetAddress.getByAddress(address);
String hostname = addr.getHostName();
if(hostname.length()>5 && (hostname.indexOf("下位機主機名")==0)){
return;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static byte[] toIpByte(String ip) {
String[] ips=ip.split("\\.");
byte[] address=new byte[ips.length];
for (int i=0;i<ips.length;i++){
address[i]=(byte) Integer.parseInt(ips[i]);
}
return address;
}
public static void main(String[] args) {
ConnectThread c = new ConnectThread();
c.start();
}
}
這種做法就是在啟動PC端的時候,pingip的時候啟動速度會略慢,會影響到客戶的體驗,所以希望一些有更好辦法的朋友,給小弟留個言,謝謝了!