Re: API to convert IP ADDress
Re: API to convert IP ADDress
- Subject: Re: API to convert IP ADDress
- From: Alastair Houghton <email@hidden>
- Date: Wed, 3 Mar 2004 11:21:10 +0000
On 2 Mar 2004, at 20:48, Sherm Pendley wrote:
>
On Mar 2, 2004, at 3:11 PM, Matt Jaffa wrote:
>
>
> convert IP Address 192.34.12.0 (for example) to the int
>
> representation of it 3495828 (something like that)
>
>
// Assuming NSString *address
>
NSArray *nums=[addr componentsSeparatedByString:@"."];
>
int rep = [[NSArray objectAtIndex:0]intValue] * 2^24 +
>
[[NSArray objectAtIndex:1]intValue] * 2^16 +
>
[[NSArray objectAtIndex: 2]intValue] * 2^8 +
>
[[NSArray objectAtIndex: 3]intValue];
This is wrong. 2^24 means 2 XOR 24, which is 26, whereas you meant
16777216, or (1 << 24). If you use constructs like this, then you
should really wrap them with a call to htonl() so that the number is
held in network byte order; it doesn't make any difference on a Mac,
because network and host order are the same, but (a) it's a good habit
to get into and (b) if you use the code on GNUStep, OpenSTEP or
NeXTSTEP, or if it gets ported to something else, then can prevent
problems with little-endian machines. It's also better to use an
unsigned rather than an int, since signedness doesn't make sense for
Internet addresses (although I realise that Matt said "int" to start
with).
>
> And also to convert the int representation of the server address
>
> back to 192.34.12.0
>
>
NSString *address = [NSString stringWithFormat:@"%u.%u.%u.%u",
>
(rep & 0xff000000) >> 24, (rep & 0x00ff0000) >> 16,
>
(rep & 0x0000ff00) >> 8, (rep & 0x000000ff)];
>
>
Untested, typed into email, etc... YMMV.
Again, there is a potential byte ordering issue should anyone ever port
this code. Also, (rep & 0xff000000) might be a negative number,
depending on the type of rep, so the first part of the address may not
be what you expect; note that this is also a portability issue, because
shifts of negative integers have implementation-defined behaviour (on
some machines [not Macs or PCs], the code above would work as you would
want it to, even if rep is -ve).
(I realise, BTW, that you typed this quickly in Mail.app, however I
think some of these points are worth highlighting for newbies, because
they aren't necessarily obvious.)
The best option, IMO, is to use the inet_pton() and inet_ntop(), or
inet_aton() and inet_ntoa() functions; the "p" functions have the
benefit that you can specify the address family, e.g. so that you can
support IPv6.
Kind regards,
Alastair.
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.