how to resolve hostname from ip address in iOS Objective-C - objective-c

I'm looking for a way to resolve the hostname of a device in my LAN from its ip address on this LAN.
I wrote a program in C which works perfectly on Linux using gethostbyaddr() function.
When I tried that on OS X or iOS it doesn't work.
It seems that there is a problem with gethostbyaddr() in OS X and iOS.
Anyway, if you have another idea to get hostname of remote machine from it's IP in iOS, it'll make my day.
This is the code I used:
First test:
192.168.0.101 is the ip address of the machine that we are querying for hostname.
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
struct hostent *he;
struct in_addr ipv4addr;
inet_pton(AF_INET, "192.168.0.101", &ipv4addr);
he = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
printf("Host name: %s\n", he->h_name);
This code works well on linux, but it doesn't on OS X nor iOS.
Second test:
+ (NSArray *)hostnamesForAddress:(NSString *)address {
// Get the host reference for the given address.
struct addrinfo hints;
struct addrinfo *result = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], NULL, &hints, &result);
if (errorStatus != 0) return nil;
CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result->ai_addr, result->ai_addrlen);
if (addressRef == nil) return nil;
freeaddrinfo(result);
CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
if (hostRef == nil) return nil;
CFRelease(addressRef);
BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
if (!isSuccess) return nil;
// Get the hostnames for the host reference.
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
NSMutableArray *hostnames = [NSMutableArray array];
for (int currentIndex = 0; currentIndex < [(NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}
return hostnames;
}
This code stucks at CFHostStartInfoResolution returning nil at this point.
Thx in advance.

It's actually a one-liner.
[[NSHost hostWithAddress:#"173.194.34.24"] name]

Related

Calling CFRelease for a CFHostRef will sometimes crash

This is a secondary question that arose out of a post I made earlier today. I have the method below, which works fine for what I need, but sometimes crashes when I call CFRelease on the hostRef variable. I think it may have to do with the resource being used elsewhere when I'm trying to release it, but as far as I can tell, I'm synchronously resolving the host and I'm not accessing it from another thread.
I tried calling CFHostCancelInfoResolution before CFRelease, but that didn't change the frequency of the crashes. I thought I would post this here to see if there are some assumptions or misconceptions I have that aren't true.
+ (NSArray *) addressesForHostname: (NSString *)hostname {
CFMutableArrayRef ipAddresses = nil;
DLog(#"Getting addresses for host name %#", hostname);
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)(hostname));
CFStreamError error;
BOOL didResolve = CFHostStartInfoResolution(hostRef, kCFHostAddresses, &error); // synchronously get the host.
if (didResolve) {
CFArrayRef responseObjects = CFHostGetAddressing(hostRef, NULL);
long numberOfResponses = CFArrayGetCount(responseObjects);
ipAddresses = CFArrayCreateMutable(kCFAllocatorDefault, numberOfResponses, &kCFTypeArrayCallBacks);
for ( int i = 0 ; i < numberOfResponses; ++i ) {
char * ipAddress = NULL;
CFDataRef responseObject = CFArrayGetValueAtIndex(responseObjects, i);
struct sockaddr * currentAddress = (struct sockaddr *) CFDataGetBytePtr(responseObject); // Unwrap the CFData wrapper aound the sockaddr struct
switch (currentAddress->sa_family) {
case AF_INET: { // Internetworking AKA IPV4
DLog(#"Extracting IPV4 address");
struct sockaddr_in * socketAddress = (struct sockaddr_in *) currentAddress;
ipAddress = malloc(sizeof(INET_ADDRSTRLEN));
inet_ntop(AF_INET,
&(socketAddress->sin_addr),
ipAddress,
INET_ADDRSTRLEN);
CFStringRef ipAddressString = CFStringCreateWithCString(kCFAllocatorDefault, ipAddress, kCFStringEncodingASCII);
CFArrayInsertValueAtIndex(ipAddresses, i, ipAddressString);
break;
}
case AF_INET6: { // IPV6
DLog(#"Extracting IPV6 address");
struct sockaddr_in6 * socketAddress = (struct sockaddr_in6 *) currentAddress;
ipAddress = malloc(sizeof(INET6_ADDRSTRLEN));
inet_ntop(AF_INET6,
&(socketAddress->sin6_addr),
ipAddress,
INET6_ADDRSTRLEN);
CFStringRef ipAddressString = CFStringCreateWithCString(kCFAllocatorDefault, ipAddress, kCFStringEncodingASCII);
CFArrayInsertValueAtIndex(ipAddresses, i, ipAddressString);
break;
}
default:
DLog(#"Unsupported addressing protocol encountered. Gracefully ignoring and continuing.");
break;
}
if(ipAddress != NULL) {
free(ipAddress);
}
}
CFRelease(responseObjects);
}
CFRelease(hostRef);
return (__bridge_transfer NSArray *) ipAddresses;
}
removing CFRelease(responseObjects); shall fix it
You must follow the Create Rule for Core Foundation objects. If you received the object by calling a function with the words Create or Copy in their names (or if you call CFRetain explicitly), then you must release (CFRelease) the object when you're done with it. If you did not receive the object this way, then you must not release the object.
There are several mistakes in your code. First, the one you're finding, which is around responseObjects. You fetch this object using:
CFDataRef responseObject = CFArrayGetValueAtIndex(responseObjects, i);
The function does not have Create or Copy in its name. You must not call CFRelease on it.
However, you also call this:
ipAddresses = CFArrayCreateMutable(kCFAllocatorDefault, numberOfResponses, &kCFTypeArrayCallBacks);
and in a couple of places:
CFStringRef ipAddressString = CFStringCreateWithCString(kCFAllocatorDefault, ipAddress, kCFStringEncodingASCII);
You must call CFRelease on these objects before they go out of scope or you will leak them.
I think CFStreamError error; may cause this issue.
Try to declare error to null?
// synchronously get the host.
BOOL didResolve = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL);

Apportable gives compile error "arithmetic on a pointer to an incomplete type"

Apportable error
arithmetic on a pointer to an incomplete type 'struct if_msghdr'
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
Here is the code. The code is working fine on ios/xcode but gives above error to interfaceMsgStruct with apportable. I have get this code from google and it is widely used so i dont think the code might have error. If it does then please correct me.
#import "MFMacAddress.h"
#implementation MFMacAddress
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
+ (NSString *)getMacAddress
{
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = #"if_nametoindex failure";
else
{
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = #"sysctl mgmtInfoBase failure";
else
{
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = #"buffer allocation failure";
else
{
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = #"sysctl msgBuffer failure";
}
}
}
// Befor going any further...
if (errorFlag != NULL)
{
NSLog(#"Error: %#", errorFlag);
return errorFlag;
}
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(#"Mac Address: %#", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
#end
To get the mac address, you can do
[[UIDevice currentDevice] macAddress]
which returns an NSString *
The compile error you're seeing is the result of a different system headers between IOS and Android. We're working on a more transparent solution, but in the meantime the solution above is an easy workaround.
Often you get this error when the definition of struct if_msghdr is not 'visible'.
Check if you need to #include other header files, or if different conditional compilation options locked it out.

Find Mac OSX serial number

How to find the Mac OSX serial number.
Sometimes it is required to get serial number of a mac, and you validate on that.
I needed the same, few years back, when I developed a plugin for OsiriX. I was asked to release it in such a way, only few systems can use that plugin.
If we get any better solution than this, that will be quite helpful for all of us.
The following code is mainly copied from Technical Note TN1103,
with small modifications to return an NSString and to make it compile with ARC:
#include <IOKit/IOKitLib.h>
- (NSString *)getSerialNumber
{
NSString *serial = nil;
io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert) {
CFTypeRef serialNumberAsCFString =
IORegistryEntryCreateCFProperty(platformExpert,
CFSTR(kIOPlatformSerialNumberKey),
kCFAllocatorDefault, 0);
if (serialNumberAsCFString) {
serial = CFBridgingRelease(serialNumberAsCFString);
}
IOObjectRelease(platformExpert);
}
return serial;
}
You have to add the IOKit.framework to your build settings.
This is the Swift version of the solution:
var serialNumber: String? {
let platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice") )
guard platformExpert > 0 else {
return nil
}
guard let serialNumber = (IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeUnretainedValue() as? String) else {
return nil
}
IOObjectRelease(platformExpert)
return serialNumber
}
This is a C++ version based on the TN1103 that Martin mention above.
C++ example:
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
std::string example_class::getSerialNumber()
{
CFStringRef serial;
char buffer[64] = {0};
std::string seriaNumber("");
io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert)
{
CFTypeRef serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert,
CFSTR(kIOPlatformSerialNumberKey),
kCFAllocatorDefault, 0);
if (serialNumberAsCFString) {
serial = (CFStringRef)serialNumberAsCFString;
}
if (CFStringGetCString(serial, buffer, 64, kCFStringEncodingUTF8)) {
seriaNumber = buffer;
}
IOObjectRelease(platformExpert);
}
return seriaNumber;
}

Obtaining a server IP address from hostname

When performing an NSURLRequest to a hostname, is it possible to obtain the IP address of the server that the response came from?
The NSURL method:
- (NSString *)host;
simply returns the hostname, and I see no way of obtaining the IP address from any of the other NSURL methods.
Perhaps there is a way of performing a host lookup before inititing the NSURLRequest?
You can use the system call gethostbyname() to resolve a hostname then use the returning structure to get the ip address. Have a look at inet_ntop() for this last part.
EXAMPLE CODE
struct hostent *hostentry;
hostentry = gethostbyname("google.com");
char * ipbuf;
ipbuf = inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0]));
printf("%s",ipbuf);
I was asking a question regarding
"how to get IP from hostname in unix\linux?"
but found this question in a different context which is not for Unix I guess, let me correct if I am wrong
since this question already been asked so I am fearing to avoid asking the same question marked as duplicated by stack overflow team.
Quest: how to get IP from hostname in unix\linux?
Ans: the two commands over there
ping host_name
Ex:
ping -s google.co.in
PING google.co.in: 56 data bytes
64 bytes from dfw06s48-in-f3.1e100.net (216.58.194.99): icmp_seq=0. time=2.477 ms
64 bytes from dfw06s48-in-f3.1e100.net (216.58.194.99): icmp_seq=1. time=1.415 ms
64 bytes from dfw06s48-in-f3.1e100.net (216.58.194.99): icmp_seq=2. time=1.712 ms
nslookup host_name
Ex:
nslookup google.co.in
Server: 155.179.59.249
Address: 155.179.59.249#53
Non-authoritative answer:
Name: google.co.in
Address: 216.58.194.99
#import <arpa/inet.h>
- (BOOL)resolveHost:(NSString *)hostname {
Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *ipAddress = nil;
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge
CFStringRef)hostname);
CFStreamError *error = NULL;
if (hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, error);
if (result) {
addresses = CFHostGetAddressing(hostRef, &result);
}
}
if (result) {
CFIndex index = 0;
CFDataRef ref = (CFDataRef) CFArrayGetValueAtIndex(addresses, index);
int port=0;
struct sockaddr *addressGeneric;
NSData *myData = (__bridge NSData *)ref;
addressGeneric = (struct sockaddr *)[myData bytes];
switch (addressGeneric->sa_family) {
case AF_INET: {
struct sockaddr_in *ip4;
char dest[INET_ADDRSTRLEN];
ip4 = (struct sockaddr_in *)[myData bytes];
port = ntohs(ip4->sin_port);
ipAddress = [NSString stringWithFormat:#"%s", inet_ntop(AF_INET, &ip4->sin_addr, dest, sizeof dest)];
}
break;
case AF_INET6: {
struct sockaddr_in6 *ip6;
char dest[INET6_ADDRSTRLEN];
ip6 = (struct sockaddr_in6 *)[myData bytes];
port = ntohs(ip6->sin6_port);
ipAddress = [NSString stringWithFormat:#"%s", inet_ntop(AF_INET6, &ip6->sin6_addr, dest, sizeof dest)];
}
break;
default:
ipAddress = nil;
break;
}
}
NSLog(#"%#", ipAddress);
if (ipAddress) {
return YES;
} else {
return NO;
}
}
[self resolveHost:#"google.com"]

How to validate an IP address with regular expression in Objective-C?

How to validate an IP address in Objective-C?
Here's a category using the modern inet_pton which will return YES for a valid IPv4 or IPv6 string.
#include <arpa/inet.h>
#implementation NSString (IPValidation)
- (BOOL)isValidIPAddress
{
const char *utf8 = [self UTF8String];
int success;
struct in_addr dst;
success = inet_pton(AF_INET, utf8, &dst);
if (success != 1) {
struct in6_addr dst6;
success = inet_pton(AF_INET6, utf8, &dst6);
}
return success == 1;
}
#end
Here's an alternative approach that might also help. Let's assume you have an NSString* that contains your IP address, called ipAddressStr, of the format a.b.c.d:
int ipQuads[4];
const char *ipAddress = [ipAddressStr cStringUsingEncoding:NSUTF8StringEncoding];
sscanf(ipAddress, "%d.%d.%d.%d", &ipQuads[0], &ipQuads[1], &ipQuads[2], &ipQuads[3]);
#try {
for (int quad = 0; quad < 4; quad++) {
if ((ipQuads[quad] < 0) || (ipQuads[quad] > 255)) {
NSException *ipException = [NSException
exceptionWithName:#"IPNotFormattedCorrectly"
reason:#"IP range is invalid"
userInfo:nil];
#throw ipException;
}
}
}
#catch (NSException *exc) {
NSLog(#"ERROR: %#", [exc reason]);
}
You could modify the if conditional block to follow RFC 1918 guidelines, if you need that level of validation.
Swift edition:
func isIPAddressValid(ip: String) -> Bool {
guard let utf8Str = (ip as NSString).utf8String else {
return false
}
let utf8:UnsafePointer<Int8> = UnsafePointer(utf8Str)
var success: Int32
var dst: in_addr = in_addr()
success = inet_pton(AF_INET, utf8, &dst)
if (success != 1) {
var dst6: in6_addr? = in6_addr()
success = inet_pton(AF_INET6, utf8, &dst6);
}
return success == 1
}
A trick you can do is test the return of the inet_aton BSD call like this:
#include <arpa/inet.h>
- (BOOL)isIp:(NSString*)string{
struct in_addr pin;
int success = inet_aton([string UTF8String],&pin);
if (success == 1) return TRUE;
return FALSE;
}
Be aware however that this validates the string if it contains a ip address in any format, it is not restricted to the dotted format.