`

获得主机名和MAC地址

    博客分类:
  • Java
阅读更多
使用getCanonicalHostName方法获得主机名

Java获取本机MAC地址
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/*
 * 物理地址是48位,别和ipv6搞错了
 */
public class LOCALMAC {
	/**
	 * @param args
	 * @throws UnknownHostException
	 * @throws SocketException
	 */
	public static void main(String[] args) throws UnknownHostException,
			SocketException {
		// TODO Auto-generated method stub

		// 得到IP,输出PC-201309011313/122.206.73.83
		InetAddress ia = InetAddress.getLocalHost();
		System.out.println(ia);
		getLocalMac(ia);
	}

	private static void getLocalMac(InetAddress ia) throws SocketException {
		// TODO Auto-generated method stub
		// 获取网卡,获取地址
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		System.out.println("mac数组长度:" + mac.length);
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			// 字节转换为整数
			int temp = mac[i] & 0xff;
			String str = Integer.toHexString(temp);
			System.out.println("每8位:" + str);
			if (str.length() == 1) {
				sb.append("0" + str);
			} else {
				sb.append(str);
			}
		}
		System.out.println("本机MAC地址:" + sb.toString().toUpperCase());
	}
}


java 获取MAC地址
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;


/**
* @title: MacAddressUtil 
* @description:获取MAC地址
* @author:liming
* @date: 2013-5-5 下午04:42:50
*/
public class MacAddressUtil{
	
	/**
	* @MethodName: getOSName 
	* @description : 获取当前操作系统名称. return 操作系统名称 例如:windows,Linux,Unix等
	* @author:liming
	* @date: 2013-5-5 下午04:43:36
	* @return String
	*/
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}
	
	/**
	* @MethodName: getWindowXPMACAddress 
	* @description : 获取widnowXp网卡的mac地址
	* @author:liming
	* @date: 2013-5-5 下午04:45:12
	* @param execStr
	* @return String
	*/
	public static String getWindowXPMACAddress(String execStr) {
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			// windows下的命令,显示信息中包含有mac地址信息
			process = Runtime.getRuntime().exec(execStr);
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				if(line.indexOf("本地连接") != -1)     //排除有虚拟网卡的情况
					continue;
				
				// 寻找标示字符串[physical address]
				index = line.toLowerCase().indexOf("physical address");
				if (index != -1) {
					index = line.indexOf(":");
					if (index != -1) {
						//取出mac地址并去除2边空格
						mac = line.substring(index + 1).trim();
					}
					break;
				}	
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			bufferedReader = null;
			process = null;
		}
		return mac;
	}
	
	/**
	* @MethodName: getWindow7MACAddress 
	* @description : 获取widnow7网卡的mac地址
	* @author:liming
	* @date: 2013-5-5 下午04:46:56
	* @param execStr
	* @return String
	*/
	public static String getWindow7MACAddress() {
		//获取本地IP对象
		InetAddress ia = null;
		try {
			ia = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		//获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
        byte[] mac = null;
		try {
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		} catch (SocketException e) {
			e.printStackTrace();
		}
        //下面代码是把mac地址拼装成String
        StringBuffer sb = new StringBuffer(); 
        for(int i=0;i<mac.length;i++){
            if(i!=0){
                sb.append("-");
            }
            //mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length()==1?0+s:s);
        }
        //把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
	}
	
	/**
	* @MethodName: getLinuxMACAddress 
	* @description : 获取Linux网卡的mac地址
	* @author:liming
	* @date: 2013-5-5 下午04:49:13
	* @return String
	*/
	public static String getLinuxMACAddress() {
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			// linux下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
			process = Runtime.getRuntime().exec("ifconfig eth0");
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				index = line.toLowerCase().indexOf("硬件地址");
				if (index != -1) {
					// 取出mac地址并去除2边空格
					mac = line.substring(index + 4).trim();
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			bufferedReader = null;
			process = null;
		}
		return mac;
	}
	
	/**
	* @MethodName: getUnixMACAddress 
	* @description : 获取Unix网卡的mac地址
	* @author:liming
	* @date: 2013-5-5 下午04:49:59
	* @return String
	*/
	public static String getUnixMACAddress() {
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			// Unix下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
			process = Runtime.getRuntime().exec("ifconfig eth0");
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				// 寻找标示字符串[hwaddr]
				index = line.toLowerCase().indexOf("hwaddr");
				if (index != -1) {
					// 取出mac地址并去除2边空格
					mac = line.substring(index + "hwaddr".length() + 1).trim();
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			bufferedReader = null;
			process = null;
		}

		return mac;
	}
	
	/**
	* @MethodName: getMacAddress 
	* @description :获取MAC地址
	* @author:liming
	* @date: 2013-5-5 下午04:53:25
	* @return String
	*/
	public static String getMacAddress(){
		String os = getOSName();
		String execStr = getSystemRoot()+"/system32/ipconfig /all";
		String mac = null;
		if(os.startsWith("windows")){
			if(os.equals("windows xp")){//xp
				mac = getWindowXPMACAddress(execStr);  
			}else if(os.equals("windows 2003")){//2003
				mac = getWindowXPMACAddress(execStr);   
			}else{//win7
				mac = getWindow7MACAddress(); 
			}
		}else if (os.startsWith("linux")) {
			mac = getLinuxMACAddress();
		}else{
			mac = getUnixMACAddress();
		}
		return mac;
	}
	
	/**
	* @MethodName: getSystemRoot 
	* @description :jdk1.4获取系统命令路径 :SystemRoot=C:\WINDOWS
	* @author:liming
	* @date: 2013-5-5 下午04:56:27
	* @return String
	*/
	public static String getSystemRoot(){
		String cmd = null;
		String os = null;
		String result = null;
		String envName = "windir";
		os = System.getProperty("os.name").toLowerCase();
		if(os.startsWith("windows")) {
			cmd = "cmd /c SET";
		}else {
			cmd = "env";
		}
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			InputStreamReader isr = new InputStreamReader(p.getInputStream());
			BufferedReader commandResult = new BufferedReader(isr);
			String line = null;
			while ((line = commandResult.readLine()) != null) {
				line=line.toLowerCase();//重要(同一操作系统不同电脑有些返回的是小写,有些是大写.因此需要统一转换成小写)
				if (line.indexOf(envName) > -1) {
					result =  line.substring(line.indexOf(envName)
							+ envName.length() + 1);
					return result;
				}
			}
		} catch (Exception e) {
			System.out.println("获取系统命令路径 error: " + cmd + ":" + e);
		}
		return null;
	}
	

}
分享到:
评论

相关推荐

    C# 获取本地IP地址以及MAC地址

    C# 获取本地IP地址以及MAC...C#获取本地IP地址和MAC地址可以通过多种方式实现,包括通过主机名获取局域网IP地址、通过局域网IP地址获取主机名和使用nbtstat命令获取MAC地址等方式。这些方法可以满足不同的需求和场景。

    JS获取客户端IP地址、MAC和主机名的7个方法汇总

    ### JS获取客户端IP地址、MAC和主机名的7个方法详解 #### 一、使用JS获取客户端IP的方法 ##### 方法一:使用ActiveX获取IP(仅适用于IE浏览器) 这种方法依赖于`ActiveXObject`来实现,因此只能在允许运行ActiveX...

    Python3获取电脑IP、主机名、Mac地址的方法示例

    本文详细介绍了如何在Python3环境中利用内置的socket和uuid模块来获取当前计算机的IP地址、主机名以及MAC地址,并通过具体代码示例展示了实现过程。这些技术点不仅有助于提升开发者在网络编程方面的技能,同时也为...

    js获取主机mac、ip、用户名、主机名

    通过js脚本获取主机mac地址、ip地址、用户名、主机名。不支持chrome浏览器,只支持IE浏览器。windows10下IE浏览器亲测有效!html文件直接拖入IE浏览器,同意相关弹窗,允许操作即可!

    LabVIEW获取主机MAC地址.rar

    在“LabVIEW获取主机MAC地址.rar”这个压缩包中,很显然,包含了一个用于获取计算机物理网络地址(即MAC地址)的LabVIEW VI。 MAC地址,全称为Media Access Control Address,是每个网络接口控制器(NIC)在硬件...

    asp.net获得用户IP和MAC地址的方法

    - 在事件处理函数`OnObjectReady`中提取MAC地址、IP地址和DNS主机名,并存储到相应的变量中。 - 最后将这些值写回到表单字段中,以便进一步处理。 3. **安全性考量:** 此类技术在实际应用中面临诸多限制和安全...

    Delphi获取MAC地址.rar

    在某些情况下,比如软件注册或设备授权,开发者可能需要获取用户的MAC地址作为硬件绑定的一种方式,防止非法复制和滥用。 在Delphi中,获取MAC地址涉及到操作系统底层的通信,这通常需要使用Windows API函数。以下...

    C#获取局域网内所有联网设备的IP地址和MAC地址

    总结,通过C#,我们可以轻松地获取局域网内设备的IP地址和MAC地址,并进行IP反向解析得到主机名。对于更复杂的网络设备发现,可能需要结合其他技术或工具。理解和掌握这些基础操作,对于网络编程和网络管理至关重要...

    C获得指定IP的MAC地址

    在计算机网络中,IP地址和MAC地址是两个关键标识符,它们用于在网络中唯一地识别设备。IP地址是网络层的逻辑地址,而MAC地址则是数据链路层的物理地址。当你需要在本地网络中与特定设备通信时,知道其IP地址是不够的...

    PB获取指定IP地址主机的MAC地址

    4. **处理结果**:解析出的MAC地址和主机名可以存储在变量中,供后续程序使用。主机名可以通过DNS或者反向ARP查询得到,但这个功能可能需要额外的网络库支持。 在描述中提到的“绝对能用”,意味着提供的代码或方法...

    记录远程登录者的IP或者MAC

    3. **查询MAC地址**:利用`NBTSTAT`命令,根据上一步得到的主机名或IP地址,查询并记录下该主机的MAC地址。 4. **写入日志文件**:将上述信息汇总后,写入到指定的日志文件中,形成一条完整的登录记录。 ### 应用...

    最好的获取MAC地址的方法

    2. **使用gethostbyaddr函数**:虽然这不是直接获取MAC地址的方法,但可以通过获取主机名然后查询DNS反向解析来间接得到。然而,这种方法并不总是可靠的,因为不是所有网络环境都支持反向DNS解析。 3. **利用PHP...

    nbtstat及netstat命令---查对方IP mac地址 根据IP查对方计算机名

    该命令的主要用途是通过 IP 地址来查找对方的计算机名和 MAC 地址。 nbtstat 命令的语法格式为: nbtstat [ [-a RemoteName] [-A IP address] [-c] [-n] [-r] [-R] [-RR] [-s] [-S] [interval] ] 其中,-a 参数...

    易语言源码取局域网内的所有计算机名、IP、网卡地址.zip

    此外,还可以利用`GetHostByName`函数或者`GetHostByAddress`函数来解析或反解析主机名或IP地址。 然后,获取网卡物理地址(MAC地址)通常是通过网络接口控制器(NIC)的驱动程序来完成的。在Windows系统中,可以...

    C#读取电脑MAC地址和IP

    在提供的压缩包文件"MACIP地址读取"中,很可能包含了一个名为"C#2010写的读取电脑MAC地址和IP程序源码"的实现,你可以解压后查看具体代码,了解作者是如何结合上述原理实现功能的。这个程序可能包含了对以上介绍的C#...

    01获得主机IP和网卡信息1

    - 对于本地IP信息的获取,首先通过`Dns.GetHostName()`得到主机名,然后调用`Dns.GetHostEntry()`得到`IPHostEntry`对象,从而获取所有IP地址。 - 使用`IPEndPoint`类创建IP端点,并展示了如何访问端点的属性,如`...

    php实现获取局域网所有用户的电脑IP和主机名、及mac地址完整实例

    在局域网中,识别和管理网络内所有设备的IP地址、主机名以及MAC地址是一项基础而重要的网络管理工作。PHP语言以其强大的网络功能,可以在服务器端实现诸多网络相关的操作。在本文中,我们将详细探讨如何利用PHP脚本...

    C#如何获得设备Mac地址.docx

    在C#编程中,获取设备的MAC(物理)地址是一个相对复杂的过程,因为与获取主机名和IP地址相比,MAC地址通常涉及到更底层的网络通信。以下将详细讲解如何使用C#来获取本地和远程设备的MAC地址。 首先,我们讨论获取...

    C#如何获得MAC识别码和IP地址

    在本篇文章中,我们将深入探讨如何使用C#编程语言来获取计算机的MAC地址(媒体访问控制地址)和IP地址(互联网协议地址)。这两个地址对于网络通信至关重要:MAC地址是物理层地址,用于局域网内的设备识别;而IP地址...

    ip mac hostname 之间相互获取方法

    在IT行业中,网络通信是至关重要的部分,而IP地址、MAC地址和主机名则是网络通信中的基础标识。本文将深入探讨如何在Windows环境下,利用VC++的MFC库以及相关的API函数,如getnameinfo和getaddrinfo,来实现IP、MAC...

Global site tag (gtag.js) - Google Analytics