C - "Vehicle endpoint not connected" after the first call to recv ()

I am just starting to learn network programming in C. I have done some tests, but I am stuck with an error.

I have a client:

client.c

#include <string.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

int main(void)
{
    struct addrinfo hints, *res;
    int sock;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    getaddrinfo("localhost", "5996", &hints, &res);
    sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    connect(sock, res->ai_addr, res->ai_addrlen);
    char data[64];
    int len = 13;
    int br = recv(sock, data, len, 0);
    printf("%s\n%s\n%d\n", strerror(errno), data, br);
    return 0;
}

and server:

server.c

#include <string.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MYPORT "5996"
#define BACKLOG 10

int main(void)
{
    struct sockaddr_storage their_addr;
    socklen_t addr_size;
    struct addrinfo hints, *res;
    int sockfd, new_fd;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    getaddrinfo(NULL, MYPORT, &hints, &res);

    sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    bind(sockfd, res->ai_addr, res->ai_addrlen);
    listen(sockfd, BACKLOG);

    addr_size = sizeof their_addr;
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);
    char *msg = "Hello World!!";
    int len = strlen(msg);
    int bs = send(new_fd, msg, len, 0);
    close(sockfd);
}

When I start the server, it waits for a connection, and if I start the client, I get the message "Hello World !!", but then, for a minute or so, if I try to start the server and then restart the client, I get the message "Transport endpoint not connected" from strerror () call .

, , , accept()... , , , ??... , - , .

+5
1

, , - . .

, setsockopt SO_REUSEADDR

sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
int reuse = 1;
int err = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
if (0 == err)
    err = bind(sockfd, res->ai_addr, res->ai_addrlen);

, . ( ) , .

+5

All Articles