I’m working with the pcap library and I’m trying to capture the source and destination IP addresses but it seems to be giving me totally random results:
Here is my struct:
struct sniff_ip {
u_char ip_vhl;
u_char ip_tos;
u_short ip_len;
u_short ip_id;
u_short ip_off;
u_char ip_ttl;
u_char ip_p;
u_short ip_sum;
struct in_addr ip_src, ip_dst;
};
Here is the relevant code that uses the struct:
void print_payload(u_char *arg, const struct pcap_pkthdr *pkthdr, const u_char *packet)
{
const struct sniff_ip *ip;
int i=0;
static int count=0;
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
printf("Source [%s] - Destination [%s]\n", inet_ntoa(ip->ip_src), inet_ntoa(ip->ip_dst));
printf("Payload:\n");
for(i=0; i<pkthdr->len; i++)
{
if(isprint(packet[i]))
printf("%c", packet[i]);
else
printf(".", packet[i]);
if((i%16 == 0 && i != 0) || ( i== pkthdr->len-1))
printf("\n");
}
}
The output is:
Source [207.117.127.0] - Destination [207.117.127.0]
Payload:
................E
..<m4@.@..u.....
.......Q@1......
....0....@......
1\.........
Source [60.190.127.0] - Destination [60.190.127.0]
Payload:
................E
..(..@.@.<......
...........Q@1.P
...wN..
The IP addresses seem to be totally random and aren’t mine. The expected output would be to show my own IP for both source and destination since I’m testing it by connecting to myself. I’m running it on port 23 to avoid anybody other data from interfering.
Edit: I got it working, for some reason I had to telnet to “eth0” instead of “localhost” for it to work. However once I changed the port to something more useful, like port 80 it worked fine. I’m not sure why port 23 was different, but oh well.
inet_ntoareturns pointer to its internal buffer, so it’s not likely that you can use twoinet_ntoas in one call toprintfand hope for different results.