Error handling in C
Nick Keighley said:
yeah, error handling in C can be a pain. Especially if you've used
something with exceptions.
...
...
To the OP, please be aware that Nick Keighley is a known troll
and is deliberately providing you with unsound advice. You asked
for error handling, not error generation (or much worse).
The code he gave you trusts the DNS server not to return an 'A'
resource record with a data length of greater than 4 bytes.
The h_length comes from a 16-bit resource-data-length field in
the DNS response message and can obviously be configured to
indicate a size much larger than 4. The end result is that
may sin.sin_addr overflow, causing a crash (or much worse).
Change that memcpy() to the following:
memcpy(&sin.sin _addr, phe->h_addr, sizeof sin.sin_addr);
In future, please post socket-related questions to both
comp.lang.c and comp.unix.progr ammer so that you get the
benefit of better peer-review. I don't read comp.unix.progr ammer,
so you might not have received this valuable information about
h_length over there, which is why you did the right thing by
posting to comp.lang.c. Besides, error handling is on-topic
here, obviously.
Yours,
Han from China
Nick Keighley said:
>I am doing some Socket Programming in C and feeling a lots of difficult in
>error handling :(
>error handling :(
something with exceptions.
You might end up with something like this:-
if ((phe = gethostbyname (host)))
memcpy (&sin.sin_add r, phe->h_addr, phe->h_length);
memcpy (&sin.sin_add r, phe->h_addr, phe->h_length);
and is deliberately providing you with unsound advice. You asked
for error handling, not error generation (or much worse).
The code he gave you trusts the DNS server not to return an 'A'
resource record with a data length of greater than 4 bytes.
The h_length comes from a 16-bit resource-data-length field in
the DNS response message and can obviously be configured to
indicate a size much larger than 4. The end result is that
may sin.sin_addr overflow, causing a crash (or much worse).
Change that memcpy() to the following:
memcpy(&sin.sin _addr, phe->h_addr, sizeof sin.sin_addr);
In future, please post socket-related questions to both
comp.lang.c and comp.unix.progr ammer so that you get the
benefit of better peer-review. I don't read comp.unix.progr ammer,
so you might not have received this valuable information about
h_length over there, which is why you did the right thing by
posting to comp.lang.c. Besides, error handling is on-topic
here, obviously.
Yours,
Han from China
Comment