Search code examples
network-programmingandroid-networking

How to send UDP packets to a MAC address from an Android app?


Is there a way to send UDP packets to a network MAC address? Neither DatagramSocket nor DatagramPacket seems to have a mechanism of doing this.


Solution

  • Because of the layered network stack, the first response is that you cannot send a UDP message to a MAC address. My statement means that you don't have any means of setting a MAC address in a UDP datagram field. You can send a UDP datagram to an IP address and port. This IP address can be unicast, multicast, or broadcast.

    If you intend to send a UDP datagram to a specific MAC address, you need to implement a more complex solution (DHCP is an example of a more complex solution). There are different strategies you can apply:

    • If you just need to send a datagram to a MAC address without having received any datagram from that NIC, and knowing that MAC address, first you will need to send a layer 2 frame to that MAC address (a layer 2 protocol allows you to set a MAC address). You can implement a protocol listening to that MAC address frames and being able to send a response back providing you the corresponding IP address. RARP is a protocol that lets you get an IP given the MAC address
    • You can implement your protocol that uses a multicast group. From your PC you send a multicast message containing the MAC address you are targeting. All nodes (applications in nodes) subscribed to that multicast group receive that message. The one with the targeted MAC address can respond. Once it responds, you have its IP address and can send a unicast UDP datagram.