Your operating system does that. How?:
Your operating system fills the macaddress for the host that you send something to or the router that is between the host.
What is the macadress when you send something in your local network
That is the host's computer macadress. How to get the macaddress from only a ipaddress?
You broadcast the ipadress to the network for macadress. Send an ARP packet to macadress FF:FF:FF:FF:FF:FF with your ipadress and wait for response. Everyone on your network will see your packet. Everybody ignores the packet except the computer with your target ip. He will response with the macaddress. Take a look at wiresharp how an ARP packet is constructed. For speed, it is important that you cache the macaddress with the ipaddress for later use.
What is the MAC address when you send/recive something outside your network
You can't get macaddresses from computers outside your network. And there is no reason to do that. If you send a packet outside your local network the MAC adress is the address of your NAT router and the ipadress outside your network. How to get the MAC address for your NAT router you just send an ARP packet with the router's IP address. In the response contains the NAT mac address. If you have the macaddress for the router you can send a packet outside your network. The NAT router will then send your packet out over the WAN side of the router.
sendto()
, who fills the MAC address in the ethernet frame? How does that accomplishes? Thank you a lot. – Peng Zhang