For Programmers: Free Programming Magazines  


Home > Archive > Unix Programming > September 2006 > recvBytes and sizeof(buf) in recvfrom()









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author recvBytes and sizeof(buf) in recvfrom()
Alex Vinokur

2006-09-27, 8:00 am

UDP socket

int sock;
char buf[512];

int recvBytes = recvfrom(sock, buf, sizeof(buf), ...);

If recvBytes > sizeof(buf) a program can crash.

How to avoid the possible crashing?


Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Maurizio Loreti

2006-09-27, 8:00 am

"Alex Vinokur" <alexvn@users.sourceforge.net> writes:

> UDP socket
>
> int sock;
> char buf[512];
>
> int recvBytes = recvfrom(sock, buf, sizeof(buf), ...);
>
> If recvBytes > sizeof(buf) a program can crash.


is it possible? my "man recvfrom" shows:

,-----
| [snip] If a message is too long to fit in the supplied buffer,
| excess bytes may be discarded depending on the type of socket the mes-
| sage is received from.
`-----

--
Maurizio Loreti http://www.pd.infn.it/~loreti/mlo.html
Dept. of Physics, Univ. of Padova, Italy ROT13: ybergv@cq.vasa.vg
Casper H.S. Dik

2006-09-27, 8:00 am

"Alex Vinokur" <alexvn@users.sourceforge.net> writes:

>UDP socket


>int sock;
>char buf[512];


>int recvBytes = recvfrom(sock, buf, sizeof(buf), ...);


>If recvBytes > sizeof(buf) a program can crash.


>How to avoid the possible crashing?


It cannot happen; if you send more bytes than the program expects,
the message will be truncated and the excess thrown away.

The sizeof (buf) argument tells the OS that "buf" is only so big
and that will prevent the OS from tryign to stuff more bytes in it
than will fit.

Casper
--
Expressed in this posting are my opinions. They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
Nils O. Selåsdal

2006-09-27, 8:00 am

Alex Vinokur wrote:
> UDP socket
>
> int sock;
> char buf[512];
>
> int recvBytes = recvfrom(sock, buf, sizeof(buf), ...);
>
> If recvBytes > sizeof(buf) a program can crash.
>
> How to avoid the possible crashing?


recvBytes can never be > sizeof(buf)
by doing recvfrom(sock, buf, sizeof(buf), ...);
you're telling recvfrom to never read more than
sizeof(buf). It can read less.

Be sure to check for errors, recvfrom can
return -1.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com