Recv gives Bad file descriptor only sometimes (run the program it works fine, sometimes it does not work)

妖精的绣舞 提交于 2019-12-25 03:36:20

问题


Scenario: I have a client (subscriber) with code that compiles and works, I have the server for said client, I can run it on different bash windows, I have printf's to show what message I'm sending, what does the server get, to see if the client receives the confirmation... Everything. There might be problems in some places of the code but more or less it works because I can send messages and so on (this is all on a local machine).

I stop the program running, execute again, and two things can happen: It works fine just as it was doing before, I can again send any message, or when I try to send from the client to the server, the server shuts down and so does the client, not receiving confirmation.

I want to explain that this happens without me compiling or doing anything whatsoever. Start the program, run again, sometimes fails.

Only thing I've got so far (since I have perror for every call I use) is:

RECV error: Bad file descriptor

That I get in this code:

 if((longitudRecibida=recv(fdSocketDevuelto, &longitudTema, sizeof(int), 0)) < 0){
        close(sock_tcp);
        perror("RECV error");
        exit(1);
      }

The reason I do not put more code is because I do not know, at all, how to reproduce the failure. Sometimes it works fine, at no point it stops, sometimes first message I send makes both process to fail.

When that happens, when I print the IP address of the client, instead of the usual 127.0.0.1 that I get, I get:

Peer IP address: 2385:6095:e37f::

To get that printed I use:

char ipstr[INET6_ADDRSTRLEN];
if (addr.ss_family == AF_INET) {
        struct sockaddr_in *s = (struct sockaddr_in *)&addr;
        port = ntohs(s->sin_port);
        inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
    } else { // AF_INET6
        struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
        port = ntohs(s->sin6_port);
        inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
    }
printf("Peer IP address: %s\n", ipstr);

I do not have a clue why a recv would work some times and not others.

edit: I can add any info requested I just don't know what I should even look for.

来源:https://stackoverflow.com/questions/29645118/recv-gives-bad-file-descriptor-only-sometimes-run-the-program-it-works-fine-so

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!