通过mac地址获取局域网IP

package com.zsy.gulimall.product.test;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通过mac地址获取局域网IP
 * 只在开发环境下生效
 * @author YuLF
 * @since 2021-01-13 10:37
 */
@Slf4j
public class LanIpResolver {


    public LanIpResolver() {
    }

    private static final Pattern IP_PATTERN = Pattern.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
    private static final Pattern MAC_PATTERN = Pattern.compile("([0-9A-Fa-f]{2})(-[0-9A-Fa-f]{2}){5}");

    /**
     * 获取本机网内地址
     */
    public static InetAddress getNet4Address() {
        try {
            //获取所有网络接口
            Enumeration<NetworkInterface> allNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
            //遍历所有网络接口
            while (allNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = allNetworkInterfaces.nextElement();
                //如果此网络接口为 回环接口 或者 虚拟接口(子接口) 或者 未启用 或者 描述中包含VM
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp() || networkInterface.getDisplayName().contains("VM")) {
                    continue;
                }
                for (Enumeration<InetAddress> netAddressEnumeration = networkInterface.getInetAddresses(); netAddressEnumeration.hasMoreElements(); ) {
                    InetAddress inetAddress = netAddressEnumeration.nextElement();
                    if (inetAddress != null) {
                        if (inetAddress instanceof Inet4Address) {
                            return inetAddress;
                        }
                    }
                }
            }
            return null;
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过mac地址获取局域网ip
     * @author YuLF
     * @since  2021/1/15 16:24
     */
    public static String getLanIpByMac(String macAddr){
        InetAddress net4Address = getNet4Address();
        assert net4Address != null;
        String hostAddress = net4Address.getHostAddress();
        log.info("局域网IP:{}", hostAddress);
        Map<String, String> ipMap = new HashMap<>(32);
        try {
            Process process = Runtime.getRuntime().exec("arp -a");
            @Cleanup InputStream is = process.getInputStream();
            @Cleanup InputStreamReader isr = new InputStreamReader(is);
            @Cleanup BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                String mac = getMac(line);
                if(mac != null){
                    ipMap.put(mac, getIp(line));
                }
            }
        } catch (IOException e) {
            log.info("com.jsy.community.utils.LanIpResolver.getLanIpByMac:获取局域网IP失败:{}", e.getMessage());
            return null;
        }
        return ipMap.get(macAddr);
    }

    public static void main(String[] args) {
        System.out.println("陈春利的IP:"+getLanIpByMac("3c-7c-3f-4b-c0-a0"));
    }

    private static String getIp(String ipStr) {
        Matcher matcher = IP_PATTERN.matcher(ipStr);
        if (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }

    private static String getMac(String ipStr){
        Matcher matcher = MAC_PATTERN.matcher(ipStr);
        if (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 你可以使用 Python 的 `scapy` 库来实现获取局域网IP地址的MAC地址。下面是一段示例代码: ```python from scapy.all import ARP, Ether, srp # 获取局域网IP地址 target_ip = input("请输入目标IP地址:") ip_prefix = target_ip.split('.')[0] + '.' + target_ip.split('.')[1] + '.' + target_ip.split('.')[2] + '.' # 创建 ARP 请求数据包 arp = ARP(pdst=ip_prefix + '0/24') ether = Ether(dst='ff:ff:ff:ff:ff:ff') packet = ether / arp # 发送 ARP 请求数据包 result = srp(packet, timeout=3, verbose=0)[0] # 解析 ARP 响应数据包 clients = [] for sent, received in result: clients.append({'ip': received.psrc, 'mac': received.hwsrc}) # 输出结果 for client in clients: print(f"IP地址: {client['ip']}, MAC地址: {client['mac']}") ``` 这段代码将会请求局域网中所有设备的IP地址和MAC地址,并将结果输出。请注意,这种方法需要在具有管理员权限的计算机上运行,以便发送 ARP 请求并接收响应。 ### 回答2: 获取局域网IP地址的MAC地址是一个较为复杂的任务,需要使用Python中的一些库和模块进行处理。下面是一个使用`scapy`库来实现获取局域网IP地址的MAC地址的代码示例: ``` from scapy.layers.l2 import Ether, ARP from scapy.sendrecv import srp def get_mac_address(ip): arp_request = ARP(pdst=ip) ether = Ether(dst="ff:ff:ff:ff:ff:ff") packet = ether/arp_request result = srp(packet, timeout=3, verbose=0)[0] mac_address = result[0][1].hwsrc return mac_address def get_local_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) local_ip = s.getsockname()[0] s.close() return local_ip if __name__ == "__main__": local_ip = get_local_ip() print("Local IP: ", local_ip) mac_address = get_mac_address(local_ip) print("MAC Address: ", mac_address) ``` 上述代码首先导入了`scapy`库中的`Ether`、`ARP`和`srp`模块来构造ARP请求,然后通过`socket`库来获取本机的IP地址。接着在`get_mac_address`函数中,首先构造了一个ARP请求包,并通过`srp`函数发送并接收ARP响应。最后,提取出MAC地址并返回。在`main`函数中,首先获取本地IP地址,然后调用`get_mac_address`函数来获取本机的MAC地址,并进行输出。 需要注意的是,使用`scapy`库需要在系统中安装该库,并且在Windows系统中可能需要以管理员权限运行代码。另外,在运行代码之前,请确保已经安装了相关的库和模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值