Search code examples
iosobjective-cnsstringunsigned

How to convert an IP address from NSString to unsigned int in Objective-C?


How to covert the IP address from NSString to unsigned int in Objective-C?

NSString A = "192.168.43.149"

And I try to convert it to unsigned int like the following code:

unsigned int ip;
ip = (unsigned int)[A intValue];

or

sscanf([A UTF8String], "%u", &ip);

The result always show only 192.

I want it show 0xc0a82b95

How to covert the IP address from NSString to unsigned int in Objective-C?

Thanks in advance.


Solution

  • For IPv4 addresses you can use inet_aton(), which converts a string to an Internet address:

    #include <arpa/inet.h>
    
    NSString *addrString = @"192.168.43.149";
    struct in_addr addr;
    if (inet_aton([addrString UTF8String], &addr) != 0) {
        uint32_t ip = ntohl(addr.s_addr);
        NSLog(@"%08x", ip);
    } else {
        NSLog(@"invalid address");
    }
    
    // Output: c0a82b95