MusiGenesis
MusiGenesis

Reputation: 75296

How to convert an unsigned int value into an IP address like 255.255.255.255?

I'm working with an API that returns a server's IP address as an unsigned int value. What's the simplest way to generate an NSString from this that displays the IP address in the format "255.255.255.255"?

Upvotes: 2

Views: 2235

Answers (3)

esmirnov
esmirnov

Reputation: 376

in_addr_t addr = your_addres_as_integer; 
const char *buf = addr2ascii(AF_INET, &addr, sizeof(addr), NULL);
NSString *result = [NSString stringWithCString:buf 
                    encoding:NSUTF8StringEncoding];

Upvotes: 4

Jasarien
Jasarien

Reputation: 58448

I've used this in the past:

- (NSString *)ip
{
    unsigned int ip = //however you get the IP as unsigned int
    unsigned int part1, part2, part3, part4;

    part1 = ip/16777216;
    ip = ip%16777216;
    part2 = ip/65536;
    ip = ip%65536;
    part3 = ip/256;
    ip = ip%256;
    part4 = ip;

    NSString *fullIP = [NSString stringWithFormat:@"%d.%d.%d.%d", part1, part2, part3, part4];

    return fullIP;
}

Upvotes: 3

codymanix
codymanix

Reputation: 29490

Iam not sure about how it is done in objective C but since it is a superset of C you can start with:

unsigned ip = whateverNumber;

char firstByte = ip & 0xff;
char secondByte = (ip>>8) & 0xff;
char thirdByte = (ip>>16) & 0xff;
char fourthByte = (ip>>24) & 0xff;

char buf[40];

sprintf(buf, "%i.%i.%i.%i", firstByte, secondByte, thirdByte, fourthByte);

The code is not tested, but should work this way.

Upvotes: 4

Related Questions