Java 通过IP地址得到对应的主机名及MAC物理地址

package com.xu.test;

import java.io.BufferedInputStream;
import java.net.InetAddress;

public class Test {
	
	public static void main(String[] args) throws Exception {
		
		getHostName("123.123.123.123");
		
	}
	
	public static String getHostName(String ip)  throws Exception {
		//局域网内通过电脑的IP来得到MAC物理地址
		Process process;
		Runtime runtime=Runtime.getRuntime();
		String mac="";
		process=runtime.exec("arp -a "+ip);
		//调用Windows电脑的 CMD.EXE来查看对应IP电脑的MAC物理地址
		BufferedInputStream macinputStream=(BufferedInputStream) process.getInputStream();
		byte [] macbt =new byte[1024];
		int len=0;
		StringBuffer macbuffer=new StringBuffer();
		while((len=macinputStream.read(macbt, 0,macbt.length))!=-1){
			macbuffer.append(new String(macbt, 0, len, "GBK"));
			//Java可能因为编码的格式与我们编写平台的编码集不同如果相同就可以不用更改
		}
		String[] macresult=macbuffer.toString().trim().split("\r\n");
		if(!macbuffer.toString().contains("未找到 ARP")){
			mac=macresult[2].substring(20, 40).trim();
		}
		System.out.println(mac);
		//通过IP来得到对应电脑的主机名字(hostname)
		InetAddress inetAddress=InetAddress.getByName(ip);
		return inetAddress.getHostName();
	}
	
}

 

 

 

你可能感兴趣的:(Java,局域网其他电脑信息获取)