Question

I had been fighting with an error in my program where I got the signal SIGPIPE when I tried to send() after connect(). The error only occurred if connect() had gotten "connection refused" at least once. Here's the old buggy code:

getaddrinfo("127.0.0.1", "1443", &hints, &res);
s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
while (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
    printf("Error: connection refused");
    sleep(2);
}   

sprintf(msg, "Testing");
msg_len = strlen(msg);
send(s, msg, msg_len, 0);

The way I fixed it seems odd to me, and I don't understand why it works. Here is the fixed code:

int connect_works = -1;
while(connect_works == -1) {
    getaddrinfo("127.0.0.1", "1443", &hints, &res);
    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    connect_works = connect(s, res->ai_addr, res->ai_addrlen);

    if (connect_works == -1) {
        printf("Error: connection refused");
        sleep(2);
    }
}

sprintf(msg, "Testing");
msg_len = strlen(msg);
send(s, msg, msg_len, 0);

To clarify, either snippet works if the first time connect() is called it returns success. However, only the second snippet works if connect() has failed one or more times.

Also, this error only occurs when compiled on Solaris. Either works when compiled on Ubuntu.

Can anyone help me understand why you must re-initialize the socket if connect() fails?

Était-ce utile?

La solution

The basic principle is that you can't re-connect a TCP socket. Once you've accepted or connected it, even with a failure, you have to close it and create a new one for new connections.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top