Thread: Question abt read(fd, buffer, 1024)

  1. #1
    Registered User
    Join Date
    Sep 2009

    Question abt read(fd, buffer, 1024)

    This is some of my code, what I want to do is keep trying to read
    information from my server until it gives me a response. But is
    this a correct way of doing it? or will it cause me problems? Cos if the
    server gives me the wrong message then i'm going to exit otherwise I'll
    process the response. So after this code I process "buffer" to determine
    my course of action.

    	write(nsFD,lookUp, strlen(lookUp));
    	//Iterate until a response is returned
    	while((numBytesRead = read(nsFD, buffer, 1024) < 0)) {


  2. #2
    Registered User
    Join Date
    Oct 2008
    No. read() will return:
    - -1 on error (look at the available errno's; some you might want to ignore and loop until you get a different result. For instance EINTR is quite useless there).
    - 0 on disconnect
    - Otherwise the number of bytes received.
    Note that read, when the socket blocks, will not return at all until it has data (or an error or end of file). So there's no reason to loop until you get anything: it only returns when you get anything.

    Your program might contain another bug that a lot of programs have and actually is ignored by most coders. If the socket is TCP, this protocol is stream based. That means that the server, if it wants to send 2 bytes, might only send 1 byte first (theoretically, although in practice I've never seen it happen). So read() might return only one byte even though the server sent two. So if you expect more bytes, keep reading until you have as much as you expect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quick C Question - checking buffer for input
    By sean in forum C Programming
    Replies: 3
    Last Post: 11-13-2004, 12:23 PM
  2. Question for network programmers
    By rtunez33 in forum Tech Board
    Replies: 6
    Last Post: 10-06-2004, 10:06 AM
  3. question abt getline
    By kashifk in forum C++ Programming
    Replies: 1
    Last Post: 09-18-2003, 07:50 PM
  4. Simple Buffer Overflow Question
    By Black-Hearted in forum C++ Programming
    Replies: 26
    Last Post: 06-15-2003, 02:51 PM
  5. what does this warningmean???
    By kreyes in forum C Programming
    Replies: 5
    Last Post: 03-04-2002, 07:53 AM