tags:

views:

85

answers:

3

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"?

+4  A: 

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.

codymanix
I believe your byte ordering is backwards. You are assigning firstByte from the least significant byte but are printing it as the most significant byte.
highlycaffeinated
+2  A: 

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;
}
Jasarien
Minor quibble: this actually produces a "backwards" IP address, but that's easily fixed by reversing the order of the parts in the string formatting call.
MusiGenesis
+1  A: 
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];
esmirnov