I’m trying to make a TCP Client program in C where the client will start up, connect to a server. Then it will send a little information and then just listen to what it receives and react accordingly.
The part that I’m having trouble with is the continuous listening. Here is what I have
... while (1) { numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0); buf[numbytes] = '\0'; printf('Received: %s\n', buf); // more code to react goes here } ...
Upon connecting to the server, after sending two lines of data, the server should receive a good bit of information, but when I run this, it prints:
Received:
And then continues to just sit there until i force it to close.
** EDIT ** when i do what Jonathan told me to do, I get the following:
Count: -1, Error: 111, Received:
So that means its erroring, but what do i do about it?
Print out the number of bytes received – it is likely to be zero, but confirm that.
It would be worth checking that you aren’t getting an error – and therefore underflowing your buffer.
[Note: from here onwards is the work of Pax – thank you, and I’ve converted it to Community Wiki so I don’t get rep points undeservedly.]
The following code will do this. Try it and report back on the results, please.
After question edit:
Error number 111 is ECONNREFUSED – this is not a usual error code for recv(), but is more suited to the open-type call (open(), connect(), etc).
In any case, ECONNREFUSED is a problem at the server end, not the client – the server has purposefully refused to accept your incoming connection, so you will need to investigate that end of the link.
In order to test this, change your code so that it’s connecting to http://www.microsoft.com on port 80, then send a couple of lines of any old rubbish. You should get back an error from their web server indicating a malformed HTTP request. This will prove there’s no problem on your client end.
This is what I get back when I
telnet www.microsoft.com 80and type inhellofollowed byENTERtwice:You should see something similar.