Convert IP address to dot syntax from unsigned long integer in iOS
Question
I'm retrieving an IP address as an unsigned long integer via JSON. I'm trying to then convert this back to human readable form, ie xxx.xxx.xxx.xxx.
Example of what I receive in JSON:
"ip": 704210705
I'm struggling a bit as C was never my forte. I'm getting an EXC Bad Access error on the below:
unsigned long int addr = [[user objectForKey:@"ip"] unsignedLongValue];
struct in_addr *remoteInAddr = (struct in_addr *)addr;
char *sRemoteInAddr = inet_ntoa(*remoteInAddr);
I get the error on the char line (3).
Can anyone give me any advice?
Solution
struct in_addr a;
a.s_addr = addr;
char *remote = inet_ntoa(a);
note that the memory pointed to by remote
is statically allocated in libc. Therefore, further calls to inet_ntoa
will overwrite the previous result.
To get the string properly into obj-c land, use
NSString *str = [NSString stringWithUTF8String:remote];
Or, putting everything together:
NSString *str = [NSString stringWithUTF8String:inet_ntoa((struct in_addr){addr})];
OTHER TIPS
Swift version, with extension.
extension UInt32 {
public func IPv4String() -> String {
let ip = self
let byte1 = UInt8(ip & 0xff)
let byte2 = UInt8((ip>>8) & 0xff)
let byte3 = UInt8((ip>>16) & 0xff)
let byte4 = UInt8((ip>>24) & 0xff)
return "\(byte1).\(byte2).\(byte3).\(byte4)"
}
}
Then
print(UInt32(704210705).IPv4String())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow