2

There are several threads about how to convert the ip-adresses in struct iphdr to strings (like 127.0.0.1) with the same method, for example:

Convert source IP address from struct iphdr* to string equivalent using Linux netfilter

But somehow they aren't working for me:

char daddr_str[16];

struct iphdr *iph = (struct iphdr*)(buf);

snprintf(daddr_str, sizeof(daddr_str), "%pI4", &iph->daddr);
printf("IP: %s\n", daddr_str);

And I get:

IP: 0x7f5870621020I

Any ideas what I did wrong?

binaryBigInt
  • 1,526
  • 2
  • 18
  • 44

2 Answers2

1

One problem could be that your are not properly extracting the IP-Header from the packet. At the beginning of the buffer usually lies the Ethernet header first and the IP header follows afterwards - so in order to get the IP-Header you need to:

struct iphdr *iph = (struct iphdr*)(buf + sizeof(struct ethhdr));

Hope it helped in your case, here is also a nice guide

Edit

You are right, this was not the actual problem in your case. I tried it out by myself and also get just the address.

After some research I think that the real cause is that these special format strings like %pI4 are only known by the kernel implementation of these functions and not by the stdlib implementation. So this attempt will only work when developing a kernel module e.g.

Community
  • 1
  • 1
Odysseus
  • 1,213
  • 4
  • 12
  • I don't think this is correct because all my other checks (sequence number and next-header type) match up. I am using a `socket(AF_INET, SOCK_RAW, IPPROTO_UDP);`. – binaryBigInt Mar 06 '20 at 09:46
0

I now did it the other way around:

struct sockaddr_in ip;

inet_aton("127.0.0.1", &ip.sin_addr);

if(ip.sin_addr.s_addr == iph->daddr) {
    ...
}
binaryBigInt
  • 1,526
  • 2
  • 18
  • 44