Socket C ++ Read Error

0

I'm developing a program in C ++ using Socket, the problem is that when the client sends some information to me I do not receive. In fact the program hangs.

#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstdlib>
#include <cstring>
#include <unistd.h>




int main(int argc, char *argv[])  {
    int socket_;
    struct sockaddr_in config;
    socklen_t config_len;

    socket_ = socket(AF_INET, SOCK_STREAM, 6);
    struct hostent *hostname = gethostbyname("127.0.0.1");
    if (socket_ < 0) {
        std::cerr << "Deu Merda AA";
    }
    config.sin_family = hostname->h_addrtype;
    config.sin_port = htons(10001);
    config.sin_addr = *((struct in_addr *) hostname->h_addr);
    bzero(&(config.sin_zero), 8);
    config_len = sizeof(config);


    std::cout << "Bind\n";
    if(int e = bind(socket_, (struct sockaddr * )&config, config_len) < 0){
        std::cerr << "Deu Merda A";
        return e;
    }

    std::cout << "Listen\n";
    if(int e = listen(socket_, 5) < 0) {
        std::cerr << "Deu Merda B";
        return e;
    }

    std::cout << "Esperando Cliente:\n";
    int client_socket = accept(socket_,(struct sockaddr * )&config, &config_len);
    std::cout << "Numero do Cliente " << client_socket << "\n";
    if(client_socket < 0){
        std::cerr << "Deu Merda C";
    }else {
        char *buffer;
        bzero(buffer, 201);
        std::cout << read(client_socket,buffer,201) << "\n";
    }

}

My Output:

Bind
Listen
Esperando Cliente:
Numero do Cliente 4

Process finished with exit code 10

The client receives the error of Broken Pipe ie the connection has dropped. But what's wrong with my code?

    
asked by anonymous 03.07.2016 / 22:54

1 answer

2

Pedro, I have an http server implemented with multiplatform sockets in c ++ but I do not use the read function that you are using, although I use recv that has a similar structure.

int recv (int __fd, void *__buf, size_t __n, int __flags)

Where we have the following points:

0) Return is the number of bytes received. (a negative return is an error)

1) The first parameter (__fd) is the file descriptor (socket number) that you are using for this connection.

2) A pointer to a buffer (I particularly use a char buffer of 4096 bytes)

3) The amount of bytes in the buffer (4096 in my case).

4) The flags to receive (particularly I have never had to use this parameter, always use ZERO (0).)

Since the function return indicates Broken Pipe it is also necessary to check what type of client is being used to connect to the server and if its implementation is compatible with yours.

    
04.07.2016 / 01:01