How to determine netmask of active interface in Objective-C on a Mac?

前端 未结 3 790
春和景丽
春和景丽 2021-02-10 17:20

I\'m trying to determine the network segment my Macbook is in, because I then want to scan this segment for active hosts (basic IP scanner) by using the CFHost class. Therefore

3条回答
  •  你的背包
    2021-02-10 17:26

    Martin had given a nice answer.
    And his code in a ARC version is here:

    + (NSDictionary *)primaryIPv4AddressInfoFromSystemConfiguration
    {
        SCDynamicStoreRef storeRef = SCDynamicStoreCreate(NULL, (CFStringRef)@"FindCurrentInterfaceIpMac", NULL, NULL);
        if (!storeRef)
        {
            return nil;
        }
    
        NSDictionary *IPv4Dictionary = nil;
        CFPropertyListRef global = SCDynamicStoreCopyValue(storeRef, CFSTR("State:/Network/Global/IPv4"));
        id primaryInterface = [(NSDictionary *)CFBridgingRelease(global) valueForKey:@"PrimaryInterface"];
        if (primaryInterface)
        {
            NSString *interfaceState = @"State:/Network/Interface/";
            interfaceState = [[interfaceState stringByAppendingString:(NSString *)primaryInterface] stringByAppendingString:@"/IPv4"];
            CFPropertyListRef IPv4PropertyList = SCDynamicStoreCopyValue(storeRef, (__bridge CFStringRef)interfaceState);
            IPv4Dictionary = (NSDictionary *)CFBridgingRelease(IPv4PropertyList);
        }
    
        CFRelease(storeRef);
        return IPv4Dictionary;
    }
    
    + (NSDictionary *)primaryIPv6AddressInfoFromSystemConfiguration
    {
        SCDynamicStoreRef storeRef = SCDynamicStoreCreate(NULL, (CFStringRef)@"FindCurrentInterfaceIpMac", NULL, NULL);
        if (!storeRef)
        {
            return nil;
        }
    
        NSDictionary *IPv6Dictionary = nil;
        CFPropertyListRef global = SCDynamicStoreCopyValue(storeRef, CFSTR("State:/Network/Global/IPv6"));
        id primaryInterface = [(NSDictionary *)CFBridgingRelease(global) valueForKey:@"PrimaryInterface"];
        if (primaryInterface)
        {
            NSString *interfaceState = @"State:/Network/Interface/";
            interfaceState = [[interfaceState stringByAppendingString:(NSString *)primaryInterface] stringByAppendingString:@"/IPv6"];
            CFPropertyListRef IPv6PropertyList = SCDynamicStoreCopyValue(storeRef, (__bridge CFStringRef)interfaceState);
            IPv6Dictionary = (NSDictionary *)CFBridgingRelease(IPv6PropertyList);
        }
    
        CFRelease(storeRef);
        return IPv6Dictionary;
    }
    

提交回复
热议问题