Information Systems

Magic packet to wakeup on LAN

This code will send a packet to a special packet to a NIC on net work 192.168.1.* to tell it to power on after it's been turned off. Change your mac[] address and the network broadcast address to suite your network. Wakeup on LAN must be set in the target computer's BIOS settings.

This type of thing is useful when you want a machine turned off to save power, while still having the ability to turn it on without physical access to the machine. Also, there are security reasons to keep computers off at certain times.

unsigned char magicPacket[102];
unsigned char mac[6];
int udpSocket;
struct sockaddr_in udpClient,udpServer;
int broadcast = 1;

for(int i = 0; i < 6; i++)
magicPacket[i] = 0xFF;

mac[0] = 0xfr;
mac[1] = 0xaa;
mac[2] = 0xcc;
mac[3] = 0xb7;
mac[4] = 0x6d;
mac[5] = 0x3b;

for(int i = 1; i <= 16; i++)
memcpy(&magicPacket[i * 6],&mac,6 * sizeof(unsigned char));

udpSocket = socket(AF_INET,SOCK_DGRAM,0);

if(setsockopt(udpSocket,SOL_SOCKET,SO_BROADCAST, (const char*) &broadcast,sizeof broadcast) == -1)
udpClient.sin_family = AF_INET;
udpClient.sin_addr.s_addr = INADDR_ANY;
udpClient.sin_port = 0;

bind(udpSocket,(struct sockaddr*)&udpClient,sizeof(udpClient));

udpServer.sin_family = AF_INET;
udpServer.sin_addr.s_addr = inet_addr("");
udpServer.sin_port = htons(9);

sendto(udpSocket, (const char*) &magicPacket,sizeof(unsigned char) * 102,0,(struct sockaddr*)&udpServer,sizeof(udpServer));