Click to See Complete Forum and Search --> : displaying source/dest ip..


threadhead
04-17-2003, 11:13 PM
that question is C related:
when i capture an ip packet off the wire and i want to display the source/dest ip address of that packet i am calling printf() like that:

printf("source ip addr: %u\n", ntohs(ip->saddr));


for the iphdr structure i included linux/ip.h.

well when i print out that address its something like 45984.
how can i print out the real ip address in x.x.x.x format?


thanks for your time!

bwkaz
04-18-2003, 10:12 AM
Take each byte of the IP address. It's probably currently declared as an unsigned long, right? The saddr field, that is.

You'll need to do the ntohl() on the field, and store that in a local unsigned long type. Then, you'll need 4 unsigned char variables (or an array of 4 unsigned chars, but I'll assume you don't use the array in the following example). Then, you extract like so:

unsigned long addr_total;
unsigned char oct1, oct2, oct3, oct4;

// ...

addr_total = ntohl(ip->saddr);

oct1 = addr_total >> 24;
oct2 = (addr_total >> 16) & 0xFF;
oct3 = (addr_total >> 8) & 0xFF;
oct4 = (addr_total) & 0xFF;

printf("source IP: %u.%u.%u.%u\n", (unsigned)oct1, (unsigned)oct2,
(unsigned)oct3, (unsigned)oct4);

threadhead
04-19-2003, 02:20 PM
a big THANK YOU to you!
it works.
i appreciate your help very much.

but i am unsure what the >> operator does.
can you maybe tell me?

thanks

bwkaz
04-19-2003, 10:41 PM
Binary shift right (assuming both arguments are numbers, or this is C code -- if it's C++ and one argument is an iostream, then it's the input operator).

It takes the binary representation of the number, and shifts it right by however many bits are in the argument. So (oct1 >> 24) results in whatever you get by shifting the binary value of oct1 right 24 bits. In this context, "right" means "toward the least-significant bit", so shifting right is like dividing by a power of 2 (2 to the 24'th if you shift 24 bits). When the ntohl() is also there, this code will work regardless of endian-ness of the processor it gets compiled for, too.

The ip->saddr field is a long integer (32 bits), where the leftmost 8 bits are the first octet of the IP address, the second 8 bits are the second octet, etc, etc. This is just extracting them one at a time.