c# 如何通过socket获取数据的源mac

如何通过socket获取通讯设备的mac,通讯的多个设备可能ip相同,怎么获取到每个设备的mac

直接做不行,mac在ip数据报里,这个东西由网卡驱动负责,你在上层获取信息实际是网卡驱动剥离IP数据报头以后的data,所以你在上层无法获取

间接手段可以有,比如封包监听工具wireshark
他使用自己的虚拟网卡驱动--为了便于理解我大体上就这么描述了---所以他可以获取剥离前的原始ip数据报,所以他可以分析到mac(当然也和应用协议有关系,icmp协议报是发mac的)

https://blog.csdn.net/qq_30033537/article/details/105349838
https://www.cnblogs.com/loveshit/p/11922925.html

上面都是理论基础,所以解决上手段
1.直接让底层给你主动发mac
2.集成类似wireshark 的底层包,直接在底层进行ip数据报分析

我现在使用PcapDevice监听数据获取mac但是出现了一个问题,就是开启监听后发送的数据一条变两条,所有数据多发送了两次。请问这是怎么回事。部分代码如下

PcapDevice _device = CaptureDeviceList.Instance[0];
_device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
_device.Open(DeviceMode.Normal, 1000);
_device.Capture(500);

//创建udp层数据包
ushort udpSourcePort = _port;
ushort udpDestinationPort = _port;
var udpPacket = new UdpPacket(udpSourcePort, udpDestinationPort);
udpPacket.PayloadData = data;

        //创建ip层数据包
        var ipSourceAddress = System.Net.IPAddress.Parse("10.0.0.31");
        var ipDestinationAddress = System.Net.IPAddress.Parse(sourceIp);
        var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);
        ipPacket.PayloadPacket = udpPacket;

        int sum1 = udpPacket.CalculateUDPChecksum();
        udpPacket.Checksum = (ushort)sum1;
        ushort sum2 = ipPacket.CalculateIPChecksum();
        ipPacket.Checksum = sum2;

        //创建链路层数据包
        var sourceHwAddress = "A4BB6DB92C06";
        var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
        var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceMac);
        var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress, ethernetDestinationHwAddress, EthernetPacketType.None);

        //数组负载数据
        ethernetPacket.PayloadPacket = ipPacket;
        byte[] packetBytes = ethernetPacket.Bytes;

        //发送sharPcap的udp命令
        _device.SendPacket(packetBytes);