user2045372
user2045372

Reputation: 1

Raw socket programming - Why does printf() affect the packet sending?

Ok, it is a very weird problem. I was trying to create a raw socket ICMP packet to spoof the ping request.

int s;
s = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);

And then

int one; // I should initialize it as 1, but I didn't. 
const int *val = &one;
setsockopt(s, IPPROTO_IP, IP_HDRINCL, val, sizeof(one));
....

It turns out that since I didn't initialize one as 1, the spoofed client cannot receive the ping reply. However, when I add a

unsigned char *ch = (unsigned char *)spoof;

just before the

close(s);,

it turns out that the spoofed client can receive the ping reply. Why is that?

Upvotes: 0

Views: 283

Answers (1)

Gene
Gene

Reputation: 47020

When you fail to initialize automatic storage, the value it gets depends on what it was last used for by your program or even the previous program that ran in the same VM space. Consequently, anything can happen. Adding the line of code just caused a different alignment of the one value on the stack. That junk in that variable in its new location allowed the raw socket to work. The other didn't. It was luck.

Upvotes: 4

Related Questions