0

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?

Govil
  • 2,034
  • 20
  • 20
  • Sorry, I haven't mentioned the printf() thing. But it will come when this first problem get some explanation. – user2045372 Feb 06 '13 at 03:42
  • Is it possible that you're running your program in debug mode? In debug mode, most compilers initialize uninitialized variables to a default value (depends on compiler). – Patashu Feb 06 '13 at 03:56

1 Answers1

4

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.

Gene
  • 46,253
  • 4
  • 58
  • 96