1

Amazingly, I have had a hard time finding an answer to this..

I have a TCP client socket that I can successfully connect with and send data through. However, after sending data, I'm expecting a response to be returned from the server. I checked my socket and it would appear that it is in non blocking mode.

if (fcntl(sc->connect_d, F_GETFL) && O_NONBLOCK)
{
//non blocking
}

What is the macro for enabling blocking mode so I can read the server response a little easier? Can somebody give me a small snippet that can do this? Thanks

tier1
  • 6,303
  • 6
  • 44
  • 75

1 Answers1

5
if (fcntl(sc->connect_d, F_GETFL) && O_NONBLOCK)

The above code is incorrect. It should be:

if (fcntl(sc->connect_d, F_GETFL) & O_NONBLOCK)

Note that TCP sockets are created in blocking mode by default, so (assuming you created the socket yourself) you shouldn't need to do anything to "put it into" blocking mode.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • Correct, I understand that. My root problem is that recv is not blocking and not returning an error code. So i'm thinking somewhere along the line it must have been set to non-blocking. – tier1 Oct 31 '13 at 17:03
  • @tkcsam - sounds like something else is going on. Sure you've not actually received some data? – Martin James Oct 31 '13 at 18:29
  • I'm receiving some data, but it is 4 bytes of junk. – tier1 Oct 31 '13 at 20:41
  • What value is recv() returning? – Jeremy Friesner Nov 01 '13 at 03:35
  • Also, what does your recv() call look like? In particular, people sometimes do a recv(mySocket, myBuffer, sizeof(myBuffer), 0); ... but if myBuffer is a pointer rather than an array, sizeof(myBuffer) will be equal to 4 (aka the size of a pointer, in a 32-bit environment) and so they don't get more than 4 bytes of data at a time that way. – Jeremy Friesner Nov 01 '13 at 03:41
  • Mostly correct answer. I would also strongly advise that you check the return value of fcntl to make sure it is not returning -1 to indicate an error. Otherwise, the bitwise AND'ing to O_NONBLOCK will be a false positive. – selbie Nov 01 '13 at 03:43