Skip to content

Instantly share code, notes, and snippets.

@johnjohndoe
Created Sep 25, 2012
Embed
What would you like to do?
Objective-C: Conversion of NetService addresses into human readable IP addresses.
//
// Host.m
// Dependencies: NSString+HexValue - Source: http://forums.macrumors.com/showthread.php?t=977076
//
#import "Host.h"
#import "NSString+HexValue.h"
#pragma mark
@interface Host()
#pragma mark
- (NSArray*)tokenizedComponentsFromAddressData:(NSData*)data atRange:(NSRange)range;
- (NSString*)formattedStringFromAddressComponents:(NSArray*)addressComponents;
@end
#pragma mark
@implementation Host
#pragma mark
- (id)init {
self = [super init];
if (self) {
m_netServiceAddressesLength16 = [NSMutableArray array];
m_netServiceAddressesLength28 = [NSMutableArray array];
m_netServiceAddressesLengthUnkown = [NSMutableArray array];
}
return self;
}
- (id)initWithNetServiceAddresses:(NSArray*)netServiceAddresses {
self = [self init];
if (self) {
for (NSData* netServiceAddress in netServiceAddresses) {
if (netServiceAddress.length == 16) {
[m_netServiceAddressesLength16 addObject:netServiceAddress];
}
else if (netServiceAddress.length == 16) {
[m_netServiceAddressesLength16 addObject:netServiceAddress];
}
else {
[m_netServiceAddressesLengthUnkown addObject:netServiceAddress];
}
}
}
return self;
}
- (NSString*)formattedIpAddressV4 {
// Select the first four bytes address. There could be more, though!
NSData* addressData = [m_netServiceAddressesLength16 objectAtIndex:0];
// Tokenize address components into strings.
// The second component (Bytes 5 till 9) contains the IP address as hexdecimal values.
NSArray* addressComponents = [self tokenizedComponentsFromAddressData:addressData atRange:NSMakeRange(5, 4)];
// Convert hexadecimal into integer values and format address.
return [self formattedStringFromAddressComponents:addressComponents];
}
#pragma mark - Helper
// Returns an array of strings, still in hexadecimal format.
- (NSArray*)tokenizedComponentsFromAddressData:(NSData*)data atRange:(NSRange)range {
NSMutableArray* result = [NSMutableArray arrayWithCapacity:range.length];
const char* bytes = [data bytes];
for (NSUInteger i = range.location; i < range.location + range.length; i++) {
[result addObject:[NSString stringWithFormat:@"%02hhx", (unsigned char)bytes[i]]];
}
return result;
}
// Returns a formatted IP address such as 192.168.23.42.
- (NSString*)formattedStringFromAddressComponents:(NSArray*)addressComponents {
NSMutableString* formattedAddress = [NSMutableString string];
for (NSUInteger index = 0; index < addressComponents.count; ++index) {
NSString* hexString = [addressComponents objectAtIndex:index];
[formattedAddress appendFormat:@"%d", [hexString hexValue]];
if (index != addressComponents.count - 1) {
[formattedAddress appendString:@"."];
}
}
return formattedAddress;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment