1 // 2C:4D:54:ED:08:F0 2 #include <stdio.h> 3 #include <Windows.h> 4 #include <winsock.h> 5 6 #pragma comment(lib,"Ws2_32.lib") 7 8 /* 9 从文件通过ip获取mac 10 ip:欲取ip的mac地址 11 成功返回对应mac,否则返回NULL. 12 */ 13 unsigned char *GetfileMacforIp(char *ip); 14 /* 15 远程唤醒 16 mac:目标mac地址 17 ps:在此之前要确保目标主板支持远程唤醒 18 */ 19 VOID RemoteStart(unsigned char *mac); 20 21 int main(void) 22 { 23 unsigned char *mac = GetfileMacforIp("172.18.1.6"); 24 if (mac) 25 { 26 printf("%X-%X-%X-%X-%X-%X ", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); 27 //free(mac); 为什么无法free? 28 } 29 system("pause"); 30 return 0; 31 } 32 33 34 35 VOID RemoteStart(unsigned char *mac) 36 { 37 // 存封包数据,格式为:6个0xFF为一组,16个mac地址为一组.mac地址正好是6个字节,封包总大小=6+16*6=102 38 unsigned char packet[102] = { 0 }; 39 struct sockaddr_in addr; 40 int sockfd, i, j; 41 const char on = 1; 42 WSADATA aaa; 43 44 // 填充封包数据 45 for (i = 0; i < 6; i++) 46 packet[i] = 0xFF; 47 for (i = 1; i < 17; i++) 48 { 49 for (j = 0; j < 6; j++) 50 { 51 packet[i * 6 + j] = mac[j]; 52 } 53 } 54 // 使用socket发送封包前必须初始化socket 55 WSAStartup(MAKEWORD(2, 2), &aaa); 56 // udp方式 57 sockfd = socket(AF_INET, SOCK_DGRAM, 0); 58 setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); 59 if (sockfd < 0) 60 { 61 printf("setsockopt filed! "); 62 return; 63 } 64 memset(&addr, 0, sizeof(addr)); 65 addr.sin_family = AF_INET; 66 addr.sin_port = htons(10000); 67 // 广播地址:255.255.255.255 68 addr.sin_addr.S_un.S_addr = inet_addr("255.255.255.255"); 69 sendto(sockfd, (const char *)packet, sizeof(packet), 0, (struct sockaddr *)&addr, sizeof(addr)); 70 WSACleanup(); 71 } 72 73 unsigned char *GetfileMacforIp(char *ip) 74 { 75 char tmp[255] = { 0 }; 76 char *pos = NULL; 77 char mac[20] = { 0 }; 78 unsigned char *mac1 = (unsigned char*)malloc(sizeof(unsigned char)*6); 79 //unsigned char mac1[6] = { 0 }; 80 81 FILE *wj = NULL; 82 fopen_s(&wj, "ipmac.txt", "r"); 83 if (!wj) 84 { 85 printf("file can`t open! "); 86 return 0; 87 } 88 while (!feof(wj)) 89 { 90 memset(tmp, 0, 255); 91 fgets(tmp, 255, wj); 92 pos = strstr(tmp, ip); 93 if (pos) 94 { 95 // 文本形式Mac地址 96 memmove(mac, tmp + strlen(ip) + 1, 17); 97 // 转字节形式Mac地址 98 sscanf_s(mac, "%x-%x-%x-%x-%x-%x", &mac1[0], &mac1[1], &mac1[2], &mac1[3], &mac1[4], &mac1[5]); 99 //printf("%X %X %X %X %X %X ",mac1[0],mac1[1],mac1[2],mac1[3],mac1[4],mac1[5]); 100 break; 101 } 102 } 103 fclose(wj); 104 return mac1; 105 }
核心函数是RemoteStart,GetfileMacforIp是我在本地存放的一个ip和mac地址的数据文件。