在网上翻来翻去,找到了部分c语言写的代码,所以采用oc,c混编
在头文件里导入需要的C.库
#include <stdio.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <net/if.h> #include <string.h> #include <unistd.h> #include <stdlib.h>
mac地址:
NSString*macStr=@"36:b2:47:f4:f4:d3";
将mac地址转换为char数组:
/*--去除字符串中的 :---*/ NSArray *macArr = [macStr componentsSeparatedByString:@":"]; NSMutableArray*arr=[macArr mutableCopy]; //修改一下格式 for (int i=0; i<arr.count; i++) { NSString*string22=[NSString stringWithFormat:@"0x%@",arr[i]]; arr[i]=string22; } //目的主机mac地址 unsigned char mac[6]; //转成char字符型 for(int i=0;i<arr.count;++i){ const char *ptr2 = [arr[i] cStringUsingEncoding:NSASCIIStringEncoding]; int ptr3; sscanf(ptr2, "%x",&ptr3); mac[i]=ptr3; }
广播域:
NSString*string=@"255.255.255.255"; const char *ptr = [string cStringUsingEncoding:NSASCIIStringEncoding];
构建魔术包:
unsigned char packet[102]; struct sockaddr_in addr; int sockfd, i,j, on = 1; for(i=0;i<6;i++){ packet[i] = 0xFF; } for(i=1;i<17;i++){ for(j=0;j<6;j++){ packet[i*6+j] = mac[j]; } }
发送:
//UDP sockfd = socket(AF_INET, SOCK_DGRAM, 0); //广播 setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST,&on, sizeof(on)); if(sockfd < 0){ exit(0); } memset((void*)&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(10000); addr.sin_addr.s_addr = inet_addr(ptr);//广播地址 sendto(sockfd, packet, sizeof(packet), 0, (struct sockaddr *)&addr, sizeof(addr)); close(sockfd);