CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2006
    Posts
    52

    Sending an int using sockets

    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:
    Code:
    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.
    Last edited by danutz_plusplus; March 8th, 2008 at 02:57 PM.

  2. #2
    Join Date
    Oct 2007
    Posts
    36

    Re: Sending an int using sockets

    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.

  3. #3
    Join Date
    Apr 2006
    Posts
    52

    Re: Sending an int using sockets

    Quote Originally Posted by verbal
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured