IP Address type?

Mar 9, 2009 at 7:58am
Hi Guys,

I am just little bit confused, what I am trying to do is, I am sending a packet across a network through my code, now when I am creating a packet, I have defined IP Address to be of the type char ipaddr[15]; It all works well and good with this, but most of the times I have seen people using unsigned long ipaddr Clearly, I think I am doing something wrong. Is it compulsory to make it unsigned long or char ipaddr[15] is fine?

I even tried to convert it using ntol() and such system calls but it keep giving error.

Any suggestions?

Thanks
Mar 9, 2009 at 12:45pm
Depends what you are using the address for.

If it's part of a struct sockaddr_in, then it has to be unsigned long.

Typically kernel system calls take IP addresses as 4-byte integers rather than strings.

ntohl stands for "network to host long" where the long refers to the fact that the function takes an (unsigned) long.
Mar 9, 2009 at 6:40pm
That's the thing, the IP address I have to use is stored in a text file. Now from the text file I have got it into a
MAP but in a string format. Now can this string IP be converted into unsigned long?

Mar 9, 2009 at 10:43pm
Parse the string.

In C,

1
2
3
unsigned char a, b, c, d;
sscanf( ipAddrString, "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d );
unsigned long ipAddr = ( a << 24 ) || ( b << 16 ) || ( c << 8 ) || d;


Mar 9, 2009 at 11:11pm
Awesome ... Thanks dude
Mar 10, 2009 at 7:17am
|| ??
Mar 10, 2009 at 12:16pm
Oops, bitwise or (|) of course.
Mar 11, 2009 at 6:01pm
I am sorry I never replied back with the corrected solution.
Topic archived. No new replies allowed.