UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2003-09-25 09:34 PM

adico
Guest

Re: socket question

#2 2003-09-26 01:25 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: socket question

Offline

#3 2004-04-14 10:43 PM

aukahi
Member
From: Honolulu
Registered: 2004-04-14
Posts: 14

Re: socket question

the recv function's prototype is as follows:

int recv(int socket_descriptor, void *buffer, size_t buffer_length, int flags);
recv returns the number of bytes read.  due to the nature of internet communication, you cannot tell garantee that you can read x bytes at 1 time.

if you have access to an unix machine, type man recv to see the flags.  otherwise, you can just put 0 (zero) in it's place.

to read 4 bytes and only 4 bytes:

int bytes = 0, bytes_read;
char buffer[4];
while (bytes_read < 4) {
    bytes = recv(sd, &buffer[bytes], sizeof(buffer) - bytes_read;
    bytes_read += bytes;
}


to read 1024 bytes at a time, just put it in a while loop like this:

char buffer[1024];
while (1)
    recv(sd, &buffer, sizeof(buffer));


please note the recv will return -1 on error.

for converting big endian to long int, i assume to you are referring to converting network-byte order to host-byte order.
use the function
unsigned long int ntohl(unsigned long int network_lonf);

Offline

#4 2004-04-15 11:51 AM

Anders Goude
Member
From: Sweden
Registered: 2002-08-01
Posts: 6

Re: socket question

int bytes, bytes_read=0; 
char buffer[4]; 
while (bytes_read < 4) { 
    bytes = recv(sd, &buffer[bytes_read], sizeof(buffer) - bytes_read,0);
    if(bytes == 0) {
         //The connection has been closed
    }
    else if(bytes == -1) {
         //There were some error
    }
    bytes_read += bytes; 
}

Offline

#5 2004-04-16 12:32 AM

aukahi
Member
From: Honolulu
Registered: 2004-04-14
Posts: 14

Re: socket question

yeah, i know, i was kind of half asleep at that time.

Offline

#6 2004-05-05 07:37 PM

sleepymish
Member
Registered: 2004-05-05
Posts: 7

Re: socket question

Offline

Board footer

Powered by FluxBB