Balaji Yalla
Balaji Yalla

Reputation: 41

how to fix connection reset by peer in C

I am trying to connect to client to server but it showing connection reset by peer

printf("Client Sends    **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", SendHeader.ProtocolVersion, SendHeader.PacketType,SendHeader.PacketLength, SendHeader.ClientId);
int ResultReceived = 0;
while (1) { 
    if ((recv(sockfd, &RecvHeader, sizeof(RecvHeader), 0)) <= 0) {
        perror("recv invalid Bet");
        close(sockfd);
        exit(1);
    }
    printf("\n\nClient Receiv`enter code `es **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** `enter code here`\n",RecvHeader.ProtocolVersion`RecvHeader.PacketType,RecvHeader.PacketLength, RecvHeader.ClientId);
    switch (RecvHeader.PacketType) {
        case BEGASEP_ACCEPT:
            printf("\n");
            Begasep_AcceptMsg AcceptMessage;
            if ((recv(sockfd, &AcceptMessage, sizeof(AcceptMessage), 0)) <= 0) {
                perror("recv");
                exit(1);

Output:

client: connecting to 127.0.0.1

Client Sends    **** |Version =  1 | Packet Type =  1 | Packet Length = 4 | ClientID = 0 |

**** recv invalid Bet: Connection reset by peer

Upvotes: 4

Views: 22281

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328760

The error means that the other side has closed the connection while you were writing more data. Whether you can do something about it on the client side depends on the reason why the receiver has closed the connection:

  • Program crashed or reboot
  • It thinks that it has got enough data
  • You told it to close the connection and then continued to use it

So the first step is to look at the remote computer if there are any errors in the log files.

The other two cases are mistakes on your side: You either send too much data or you didn't implement the protocol correctly. Examples are: Server expects "number of bytes" and then N bytes of data. You send "8" and then 10 bytes. After 8 bytes, the other side will stop.

Other protocols have "quit" or "bye" commands which cause the other side to close the connection. If you try to send more data after that, that will fail.

Upvotes: 5

Related Questions