开发者

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开发者_StackOverflow from this that displays the IP address in the format "255.255.255.255"?


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.


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];


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜