Twisted89
Twisted89

Reputation: 446

Winsock TCP connection, send fine but recv firewall blocked

I have an application that sends a GET request using winsock on port 80 using a TCP socket. A few users have reported an issue where no response is received, looking at network logs and seeing the network device is getting the data just the app isn't it was clear that the firewall was blocking it.

Having disabled the firewall it then worked fine but what I don't understand is why it was getting blocked. The connection is created from the users computer, it connects fine and sends (which I assumes automatically opens a port) so how can data be lost on the same connection when received? Should I be providing additional winsock settings? Or is there simply no way around stopping the firewall blocking an already active connection?

Here is a stripped down version of the winsock code

SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
    return -1;


struct sockaddr_in client;
memset(&client, 0, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(80);
client.sin_addr.s_addr = inet_addr(inet_ntoa(*addr_list[0]));

if (connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0){
    closesocket(sock);
    return -1;
}

if (send(sock, buffer, buflength, 0) != buflength){
    closesocket(sock);
    return -1;
}

//get response
response = "";
int resp_leng = BUFFERSIZE;
while (resp_leng == BUFFERSIZE)
{
    resp_leng = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
    if (resp_leng > 0)
        response += std::string(buffer).substr(0, resp_leng);
    else
        return -1;
}

closesocket(sock);

Upvotes: 0

Views: 434

Answers (1)

keithmo
keithmo

Reputation: 4943

Your while loop exits if a recv() returns less than BUFFERSIZE. This is wrong -- you must always assume that recv() can return any amount of data from 1 byte up to and including the supplied buffer size.

Upvotes: 1

Related Questions