Click to See Complete Forum and Search --> : Sending an int using sockets


danutz_plusplus
March 8th, 2008, 12:53 PM
Hi. I've searched for this for a bit, and couldn't find a thread about it. Sorry if I missed it.

Anyway, here's my problem. I'm trying to send integers over a network using sockets, and I found a code sample that apparently does that(though I didn't test it yet, so I'm not sure), but I can't understand some of the code. And I thought someone might be so kind as to explain it to me. Or if the code is incorrect maybe someone could tell how exactly do I send an int using socket. I can send char[] easily, but I just can't do it with ints.

Here's the code sample:

int n;

n=555;

if(send(socket,&n,4,0) <4)
{
// we have problem, must use connect before it!??
}

close(socket);
-----

int n;
if(recv(socket,&n,4,0)) < 4)
{

cycle until got 4
}

close
print(n)

What I mainly don't understand is the &n part, but could someone also explain what the whole if does? I guess the 4s are for the nr of bytes that are in an int. Thanks.:)

verbal
March 9th, 2008, 08:02 PM
ok , probably whoever posted this code got confused with html or something...
The &amp; logically represents the '&' sign for the address of n and the &lt is the '<' sign.

so basically you have your int and then you point to the address of n and send 4 bytes which is the default int size in most architectures (with some exceptions always).
The recv part is basically the same...

when you use send() and recv() you send bytes, how you will treat the bytes you send and recv depend on you.

danutz_plusplus
March 10th, 2008, 01:08 AM
ok , probably whoever posted this code got confused with html or something...
The &amp; logically represents the '&' sign for the address of n and the &lt is the '<' sign.

so basically you have your int and then you point to the address of n and send 4 bytes which is the default int size in most architectures (with some exceptions always).
The recv part is basically the same...

when you use send() and recv() you send bytes, how you will treat the bytes you send and recv depend on you.
Thanks for clearing that up. :) It makes a lot of sense. :)