android firmware 利用UDP socket发送Magic Packet--c语言版本

android firmware 利用UDP socket发送Magic Packet

1 Magic Packet格式:

  6个0xFF + 16个Dst Mac Address

2 代码需要设置目的MAC地址, 目的IP地址和使用的端口

 1 #include <stdio.h> 
 2 #include <string.h> 
 3 #include <stdlib.h> 
 4 #include <unistd.h> 
 5 #include <sys/types.h> 
 6 #include <sys/stat.h> 
 7 #include <sys/socket.h> 
 8 #include <netinet/in.h> 
 9 #include <arpa/inet.h> 
10 #include <netdb.h> 
11 
12 void generate_magic_packet(void *magic_buf, void *mac) 
13 { 
14          int i; 
15          char *ptr; 
16 
17          ptr = magic_buf; 
18          memset(ptr, 0xFF, 6); 
19          ptr += 6; 
20 
21          for(i = 0; i < 16; ++i) { 
22                  memcpy(ptr, mac, 6); 
23                  ptr += 6; 
24          } 
25 } 
26 
27 int main(int argc, char **argv) 
28 { 
29          int s; 
30          int packet_num = 10; 
31          char c; 
32 
33          unsigned char mac[6] = {0x94, 0x39, 0xE5, 0x02, 0x5E, 0xC9}; 
34          char dstip[256] = "192.168.1.106"; 
35          int port = 1900; 
36 
37          struct sockaddr_in address; 
38          char magic_buf[6 + 6 * 16] = {0}; 
39 
40          daemon(0,0);    /* run in background */ 
41 
42          s = socket(AF_INET, SOCK_DGRAM, 0); 
43          if (s == -1) { 
44                  perror("Opening socket"); 
45                  exit(EXIT_FAILURE); 
46          } 
47 
48          memset(&address, 0, sizeof(struct sockaddr_in)); 
49          address.sin_family = AF_INET; 
50          address.sin_addr.s_addr = inet_addr(dstip); 
51          address.sin_port = htons(port); 
52 
53          generate_magic_packet(magic_buf, mac); 
54 
55          /* ten packets. TODO: use ping to check whether the destination is on or else. */ 
56          while (packet_num-- > 0) { 
57                  if (sendto(s, magic_buf, sizeof(magic_buf), 0, 
58                       (struct sockaddr *)&address, sizeof(address)) < 0) { 
59                          printf("sendto
"); 
60                          exit(EXIT_FAILURE); 
61                  } 
62                  sleep(1); 
63          } 
64 
65          exit(EXIT_SUCCESS); 
66 } 
原文地址:https://www.cnblogs.com/xuhaohunter/p/5611593.html