3

I have a client and a server using sockets on windows. I start the server before the client, wait for it to hang and then start the client. Doing so, the call to recv() will randomly (half of the time) return -1 and when I print errno it is at 0 (No Error)... The other half of the time it will receive the message and print it normally then close... Is there something wrong with this code ?

client.c

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <errno.h>

#define BUFFER_LEN 200

int main()
{
    WSADATA WSAData;
    WSAStartup(MAKEWORD(2,0), &WSAData);
    
    SOCKET sock;
    SOCKADDR_IN address;
    // address.sin_addr.s_addr = inet_addr("127.0.0.1");
    InetPton(AF_INET, "127.0.0.1", &address.sin_addr.s_addr);
    address.sin_family = AF_INET;
    address.sin_port = htons(8888);
    
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        printf("Erreur lors de la création du socket. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    if ((connect(sock, (SOCKADDR *)&address, sizeof(address))) == -1) {
        sprintf("Erreur lors de la connexion au socket. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    char *msg = "Coucou\n";
    printf("Envoi de coucou\n");
    int bytesSent;

    if ((bytesSent = send(sock, msg, strlen(msg), 0)) == -1) {
        sprintf("Erreur lors l'envoi du message. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    printf("Bytes envoyés : %d\n", bytesSent);

    WSACleanup();
    
    return 0;
}

server.c

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define BACKLOG 3 // taille de la file d'attente
#define BUFFER_LEN 200 // taille du buffer de lecture

int main()
{
    WSADATA WSAData;
    WSAStartup(MAKEWORD(2,0), &WSAData);
    
    SOCKET sockfd;
    SOCKADDR_IN address;
    // address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_addr.s_addr = htonl(INADDR_ANY);  
    address.sin_family = AF_INET;
    address.sin_port = htons(8888); // host to network short (conversion de host byte order en network byte order)
    
    printf("Démarrage du serveur\n");

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        printf("Erreur lors de la création du socket. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    if ((bind(sockfd, (SOCKADDR *)&address, sizeof(address))) == -1) {
        printf("Erreur lors de l'ouverture du socket. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    if ((listen(sockfd, BACKLOG)) == -1) {
        printf("Erreur lors de l'écoute du socket. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    SOCKET clientSocket;
    SOCKADDR_IN clientAddress;
    int addrLen = sizeof(clientAddress);
    if ((clientSocket = accept(sockfd, (struct sockaddr *) &clientAddress, &addrLen)) == -1) {
        printf("Erreur lors de l'acceptation de la connexion. %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    // Convertion de l'IP en texte
    char ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(clientAddress.sin_addr), ip, INET_ADDRSTRLEN);
    printf("Connexion de %s:%i\n", ip, clientAddress.sin_port);

    char buffer[BUFFER_LEN];
    int len = recv(clientSocket, buffer, BUFFER_LEN, 0);

    if (len == -1 && errno != EAGAIN) {
        printf("Erreur lors de la réception du message. %s (%d)\n", strerror(errno), errno);
        exit(EXIT_FAILURE);
    } else if (len == 0) {
        printf("Le client s'est déconnecté (extrémité de la socket fermée)\n");
        exit(EXIT_FAILURE);
    } else if (len > 0) {
        printf("Message reçu : %s\n", buffer);
    }

    closesocket(clientSocket);
    closesocket(sockfd);

    WSACleanup();

    return 0;
}

I also should mention that I compile with gcc main.c -lws2_32 -g -Wall

5
  • 1
    I don't have Windows to test this on, but your client sends some data and then immediately exits (without closing the socket). Maybe that is destroying the socket before it has actually sent the data. Maybe adding a close() or a delay would fix it. Commented Jun 8, 2023 at 20:39
  • 3
    Quote: Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError Commented Jun 8, 2023 at 20:58
  • That was it @pmacfarlane, thanks. You can post this as an answer and I'll accept it. Thank you also Hans, I'll try this out.
    – Leogout
    Commented Jun 8, 2023 at 21:03
  • On a side note, there is no EAGAIN on Windows. If a non-blocking socket (and FYI, you are not using non-blocking sockets) encounters a blocking operation, WSAEWOULDBLOCK is reported. Commented Jun 8, 2023 at 21:19
  • Thank you, this all makes sense now. It seems that making native sockets cross platform is a real challenge. I'll stick to the Windows documentation now and stop mixing UNIX tutorials with it.
    – Leogout
    Commented Jun 8, 2023 at 21:23

1 Answer 1

5

The first thing to note is that when the call to send() in your client returns, this does not mean that any data has been sent to your server. It just means the data has been queued up to be sent.

Your client then immediately calls WSACleanup() and exits. It would appear that this just instantly destroys your socket, before it has had a chance to send anything.

You should add closesocket(sock) between sending your data, and calling WSACleanup(). This will allow the socket to be closed in an orderly manner, including flushing any data that has been queued up.

As pointed out by @Hans, reading errno is not the correct way to get a socket error, you should use WSAGetLastError().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.