IOS 手机端搜索硬件设备 --- 物联网

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<errno.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<unistd.h>

//pch 文件导入

//扫描本地设备 --- 智能家居

-(void)scanLocalDevice

{

NSLog(@"开始扫描本地设备");

setvbuf(stdout, NULL, _IONBF, 0); // 不要缓冲区

fflush(stdout); // 清除缓冲区

int sock = -1;

//AF_INET : #define AF_INET 2 // internetwork: udp, tcp, etc.

// SOCK_DGRAM是基于UDP的,专门用于局域网,基于广播

// 0 : 调用的协议

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)

{

return;

}

const int opt = 1;

//设置该套接字为广播类型,

int nb = 0;

nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));

struct sockaddr_in addrto;

bzero(&addrto, sizeof(struct sockaddr_in));

addrto.sin_family=AF_INET;

addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST); // //广播地址:255.255.255.255

addrto.sin_port=htons(1025);

int nlen=sizeof(addrto);

while(1)

{

totalSearchTime += 1;

NSLog(@"-->%d",totalSearchTime);

sleep(1);

//从广播地址发送消息

char smsg[] = {"Are You Espressif IOT Smart Device?"};//与硬件约定的响应消息 硬件收到广播之后主动广播回主动发送自己的mac的地址和ip地址

long ret=sendto(sock, smsg, strlen(smsg), 0, (struct sockaddr*)&addrto, nlen);

if(ret<0){

}

else{

socklen_t size;

char buf[MAXDATASIZE];

memset(buf, 0, MAXDATASIZE);

recvfrom(sock,buf,MAXDATASIZE,0,(struct sockaddr *)&addrto,&size);

NSString *str = [NSString stringWithFormat:@"%s",buf];

NSArray * arry = [str componentsSeparatedByString:@" "];

NSString *tempstr = arry[1];

NSString *ip = arry[2];

NSRange range = [tempstr rangeOfString:@"."];

range.length = range.location;

range.location = 0;

range.location=range.length+1;

range.length = [tempstr length] - range.location;

NSString *mac = [tempstr substringWithRange:range];

NSArray *arr = [NSArray arrayWithObjects:ip,mac, nil];

NSLog(@"----------->   扫描到的IP 和 MAC --->IP = %@ Mac = %@",ip,mac);

[ListArray addObject:arr];

if (totalSearchTime == 20) {

totalSearchTime = 0;

[self getEqupmentIP];

break;

}

}

}

}

上一篇:Android中 View not attached to window manager错误的解决办法


下一篇:Android中View和ViewGroup介绍