PDA

View Full Version : large packet structure TCP


Aaron
03-06-2003, 08:26 PM
I'm trying to send large packets on a TCP connection. When I recv these on the other side I need to know what size they are.. the size will need to be at least 2 bytes long. so I need to know how to convert a short int into 2 bytes to stick on the front of the packet. Any suggestions on a better way to deal with big packets would also be appreciated.

RobSeace
03-06-2003, 10:15 PM
The only conversion you might want to do to the short int is call
htons() on it (then, the receiver would call ntohs() after reading it)...
Otherwise, you can just send the raw short... Eg:


short msgsize, nmsgsize;

/* ...set msgsize by whatever means to real size of message... */

nmsgsize = htons (msgsize);
write (fd, &nmsgsize, sizeof (nmsgsize));
write (fd, msg, msgsize);


Or, if you've got TCP_NODELAY set, you probably want to change
those two separate write()/send() calls into a single writev()/sendmsg(),
to prevent an extra packet for the tiny message header...

Aaron
03-07-2003, 05:43 AM
Thanks, but I'm unfamiliar with the write() function. Can you give me an example of how to use this to send a packet like the following:
short size = 300;
std::string msg = "some string 298 bytes long.....";

.. also is the write function available with all unix? I can't seem to find it in man pages for freeBSD.

RobSeace
03-07-2003, 01:19 PM
You can't find a man page for write()???? Either you're not looking in
the right place, or they've got incomplete man pages, because I've
never heard of any system in existence without write()...

But, if you prefer to use send(), go right ahead... No difference, unless
you use some of the send() flags... I just used write() in my examples,
because that's generally my preference... But, it makes no difference...

But, by your "std::string", I'll assume you're in C++ land... A land I
dislike... ;-) I can only show you straight C code... You're on your own
with dealing with C++ nonsense... My code was assuming "msg" was
a straight char* or char[] buffer (or something that could easily be
treated as such, at least)... However, the htons()/ntohs() stuff still
applies, which is what you asked about originally...

But, to convert the previous write()s to send()s is just a simple matter:


send (fd, &nmsgsize, sizeof (nmsgsize), 0);
send (fd, msg, msgsize, 0);

x33
04-07-2003, 10:33 AM
Well... you can use a c_string() method of the std::string class. It returns a classical null-terminated c-string. And you can then use it with the standart c-functions.