代碼鏈接 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;
}
