Created
April 6, 2020 06:11
-
-
Save czs0x55aa/3a3d027f95f9e9680cb67acc830accce to your computer and use it in GitHub Desktop.
wake on lan using ethernet frame in windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <pcap.h> | |
u_char char_to_hex(char c) | |
{ | |
if (c >= '0' && c <= '9') | |
{ | |
return c - '0'; | |
} | |
else if (c >= 'A' && c <= 'F') | |
{ | |
return c - 'A' + 0xa; | |
} | |
else if (c >= 'a' && c <= 'f') | |
{ | |
return c - 'a' + 0xa; | |
} | |
return 0; | |
} | |
void mac_to_hex(char* str_mac, u_char* dst_data) | |
{ | |
dst_data[0] = (char_to_hex(str_mac[0]) << 4) + char_to_hex(str_mac[1]); | |
dst_data[1] = (char_to_hex(str_mac[3]) << 4) + char_to_hex(str_mac[4]); | |
dst_data[2] = (char_to_hex(str_mac[6]) << 4) + char_to_hex(str_mac[7]); | |
dst_data[3] = (char_to_hex(str_mac[9]) << 4) + char_to_hex(str_mac[10]); | |
dst_data[4] = (char_to_hex(str_mac[12]) << 4) + char_to_hex(str_mac[13]); | |
dst_data[5] = (char_to_hex(str_mac[15]) << 4) + char_to_hex(str_mac[16]); | |
} | |
int main(int argc, char** argv) | |
{ | |
pcap_t* fp; | |
char errbuf[PCAP_ERRBUF_SIZE]; | |
u_char packet[200]; | |
//char pSource[] = "rpcap://\\Device\\NPF_{82f71d8f-5ed1-4aa9-a247-bda3db206c40}"; | |
if (argc < 4) | |
{ | |
fprintf(stderr, "usage:\nwin_wol.exe device_id src_mac dst_mac"); | |
return 0; | |
} | |
if (strlen(argv[2]) != 17 || strlen(argv[3]) != 17) | |
{ | |
fprintf(stderr, "illegal mac address format, src_mac: %s, dst_mac: %s\n", argv[2], argv[3]); | |
return 0; | |
} | |
std::string strSource = "rpcap://\\Device\\NPF_{" + std::string(argv[1]) + "}"; | |
u_char src_mac[7] = { 0xd0, 0xc6, 0x37, 0x05, 0x68, 0xa6, 0 }; | |
u_char dst_mac[7] = { 0x8c, 0x16, 0x45, 0x90, 0x1d, 0x8e, 0 }; | |
mac_to_hex(argv[2], src_mac); | |
mac_to_hex(argv[3], dst_mac); | |
if ((fp = pcap_open(strSource.c_str(), | |
100, | |
PCAP_OPENFLAG_PROMISCUOUS, | |
1000, | |
NULL, | |
errbuf | |
)) == NULL) | |
{ | |
fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", argv[1]); | |
return 0; | |
} | |
// dst mac | |
memset(packet, 0xff, 6); | |
// memcpy(packet, dst_mac, 6); | |
// src mac | |
memcpy(packet + 6, src_mac, 6); | |
// WOL protocol | |
packet[12] = 0x08; | |
packet[13] = 0x42; | |
// sync stream | |
memset(packet + 14, 0xff, 6); | |
int baseidx = 20; | |
for (int i = 0; i < 16; ++i) | |
{ | |
memcpy(packet + baseidx, dst_mac, 6); | |
baseidx += 6; | |
} | |
if (pcap_sendpacket(fp, packet, baseidx) != 0) | |
{ | |
fprintf(stderr, "\nError sending the packet: %s\n", pcap_geterr(fp)); | |
return 0; | |
} | |
std::cout << "Done\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment