呸!!经过大量谷歌搜索和试错方法后,我找到了解决方案。解决方案来了。
首先使用以下函数枚举所有可用的网络接口。
- (NSMutableArray *) enumerateAndGetDetailsOfAllNetworkInterfaces
{
NSMutableArray *interfaceArray = [[NSMutableArray alloc] init];
struct ifaddrs *ifap, *ifa;
struct sockaddr_in *sa;
char *addr;
getifaddrs (&ifap);
for (ifa = ifap; ifa; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr->sa_family==AF_INET)
{
QNInterfaceModel *interfaceModel = [[QNInterfaceModel alloc] init];
sa = (struct sockaddr_in *) ifa->ifa_addr;
addr = inet_ntoa(sa->sin_addr);
printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
interfaceModel.interfaceName = [NSString stringWithCString:ifa->ifa_name encoding:NSUTF8StringEncoding];
interfaceModel.interfaceIPAddress = [NSString stringWithCString:addr encoding:NSUTF8StringEncoding];
[interfaceArray addObject:interfaceModel];
}
}
freeifaddrs(ifap);
return interfaceArray;
}
我创建了存储接口名称及其地址的 InterfaceModel。
第 2 步:为每个接口创建一个套接字
NSMutableArray *interfaceArray = [self enumerateAndGetDetailsOfAllNetworkInterfaces];
for(QNInterfaceModel *interfaceModel in interfaceArray)
{
NSError *error;
NSInteger udpPort = 8097;
GCDAsyncUdpSocket *gcdAsyncUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
delegateQueue:dispatch_get_main_queue()];
[gcdAsyncUdpSocket bindToPort:udpPort interface:interfaceModel.interfaceName error:&error];
gcdAsyncUdpSocket.delegate = self;
if(error == nil)
{
[_socketArray addObject:gcdAsyncUdpSocket];
}
}
步骤 3:将所有创建的套接字存储在一个数组中,并通过每个套接字进行广播,如下所示,但在广播之前,我们需要创建一个侦听器套接字来接收响应数据包。
NSError *error;
NSString *broadCastString = @"255.255.255.255";
NSInteger udpPort = 8097;
GCDAsyncUdpSocket *listenerGCDAsyncUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
delegateQueue:dispatch_get_main_queue()];
[listenerGCDAsyncUdpSocket bindToPort:udpPort error:&error];
[listenerGCDAsyncUdpSocket setPreferIPv4];
[listenerGCDAsyncUdpSocket enableBroadcast:YES error:&error];
[listenerGCDAsyncUdpSocket beginReceiving:&error];
// Send Packets through all the available Interfaces
for(NSInteger i =0 ; i<_socketArray.count ;i++)
{
GCDAsyncUdpSocket *gcdAsyncUdpSocket = [_socketArray objectAtIndex:i];
gcdAsyncUdpSocket.delegate = self;
if(error)
{
// Error connecting
}
else
{
[gcdAsyncUdpSocket setPreferIPv4];
NSData *data = @"Hi There";
if (![gcdAsyncUdpSocket enableBroadcast:YES error:&error]) {
QNDLog(@"Error enableBroadcast:%@",error);
return;
}
[gcdAsyncUdpSocket beginReceiving:&error];
[gcdAsyncUdpSocket sendData:data toHost:broadCastString port:udpPort withTimeout:-1 tag:i];
}
}