您的位置:首页 > 移动开发 > IOS开发

ios开发UDP协议发送广播寻找设备

2016-02-23 11:18 393 查看
原文链接:https://www.geek-share.com/detail/2667197481.html

代码链接  http://files.cnblogs.com/files/godlovexq/UDP.zip

 

#import "AsyncUdpSocket.h"

#import <ifaddrs.h>

#import <arpa/inet.h>

//做udp 请求

-(void)MakeUDP

{

    //实例化

    AsyncUdpSocket *socket=[[AsyncUdpSocket alloc]initWithDelegate:self];

    //启动本地端口

    [socket localPort];

 

    NSTimeInterval timeout=1000;//发送超时时间

    

    NSString *request=@"dongqiangfei";//发送给服务器的内容

    

    NSData *data=[NSData dataWithData:[request dataUsingEncoding:NSASCIIStringEncoding] ];

    

    UInt16 port=6000;//端口

    

    NSError *error;

    

    //发送广播设置

    [socket enableBroadcast:YES error:&error];

    //@"10.10.60.255"

    //把得到的目标ip 最后的数字更换为255(意思是搜索全部的)

    NSArray *strArr=[[self getIPAddress] componentsSeparatedByString:@"."];

    NSMutableArray *muArr = [NSMutableArray arrayWithArray:strArr];

    [muArr replaceObjectAtIndex:(strArr.count-1) withObject:@"255"];

    NSString *finalStr = [muArr componentsJoinedByString:@"."];//目标ip

    

    /*

     发送请求

     sendData:发送的内容

     toHost:目标的ip

     port:端口号

     timeOut:请求超时

     */

    BOOL _isOK = [socket sendData :data toHost:[NSString stringWithFormat:@"%@",finalStr] port:port withTimeout:timeout tag:1];

    if (_isOK) {

        //udp请求成功

    }else{

        //udp请求失败

    }

    

    [socket receiveWithTimeout:1000 tag:0];//启动接收线程 - n?秒超时

    

    NSLog(@"开始啦");

}

 

//接受信息

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{

    

    NSString* result;

    

    result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    

    NSLog(@"%@",result);

    

    NSLog(@"%@",host);

    

    NSLog(@"收到啦");

    

    return NO;

}

 

//接受失败

-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{

    

    NSLog(@"没有收到啊 ");

}

 

//发送失败

-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{

    

    NSLog(@"%@",error);

    

    NSLog(@"没有发送啊");

    

}

 

//开始发送

-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{

    

    NSLog(@"发送啦");

}

 

//关闭广播

-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{

    

    NSLog(@"关闭啦");

}

 

#pragma mark 获取当前IP

- (NSString *)getIPAddress {

    NSString *address = @"error";

    struct ifaddrs *interfaces = NULL;

    struct ifaddrs *temp_addr = NULL;

    int success = 0;

    // retrieve the current interfaces - returns 0 on success

    success = getifaddrs(&interfaces);

    if (success == 0) {

        // Loop through linked list of interfaces

        temp_addr = interfaces;

        while(temp_addr != NULL) {

            if(temp_addr->ifa_addr->sa_family == AF_INET) {

                // Check if interface is en0 which is the wifi connection on the iPhone

                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {

                    // Get NSString from C String

                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;

        }

    }

    // Free memory

    freeifaddrs(interfaces);

    return address;

}

 

转载于:https://www.cnblogs.com/godlovexq/p/5209270.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: