/* tools/junction-wol.c — send a Wake-on-LAN magic packet. * * junction-wol aa:bb:cc:dd:ee:ff [broadcast] [port] * * C99 + POSIX like the router itself. Hooks may be shell, but they are not allowed * to need a Python interpreter to build a 102-byte packet. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include static int hexval(int c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "usage: junction-wol aa:bb:cc:dd:ee:ff [broadcast] [port]\n"); return 2; } unsigned char mac[6]; int n = 0; for (const char *p = argv[1]; *p && n < 6; ) { int hi = hexval((unsigned char)*p++); int lo = *p ? hexval((unsigned char)*p) : -1; if (hi < 0 || lo < 0) { fprintf(stderr, "bad_mac: %s\n", argv[1]); return 2; } mac[n++] = (unsigned char)((hi << 4) | lo); if (*p) p++; if (*p == ':' || *p == '-') { p++; continue; } if (*p) { fprintf(stderr, "bad_mac: %s\n", argv[1]); return 2; } } if (n != 6) { fprintf(stderr, "bad_mac: %s\n", argv[1]); return 2; } unsigned char pkt[102]; memset(pkt, 0xff, 6); for (int i = 0; i < 16; i++) memcpy(pkt + 6 + i * 6, mac, 6); const char *bcast = argc > 2 ? argv[2] : "255.255.255.255"; int port = argc > 3 ? atoi(argv[3]) : 9; int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); return 1; } int one = 1; setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one); struct sockaddr_in to; memset(&to, 0, sizeof to); to.sin_family = AF_INET; to.sin_port = htons((unsigned short)port); if (inet_pton(AF_INET, bcast, &to.sin_addr) != 1) { fprintf(stderr, "bad_broadcast: %s\n", bcast); close(fd); return 2; } if (sendto(fd, pkt, sizeof pkt, 0, (struct sockaddr *)&to, sizeof to) < 0) { perror("sendto"); close(fd); return 1; } if (port == 9) { /* many NICs listen on 7, a few only there */ to.sin_port = htons(7); (void)sendto(fd, pkt, sizeof pkt, 0, (struct sockaddr *)&to, sizeof to); } close(fd); printf("sent %s via %s:%d\n", argv[1], bcast, port); return 0; }