0
I am 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 Way out:
Bind
Listen
Esperando Cliente:
Numero do Cliente 4
Process finished with exit code 10
The customer receives the error of Broken Pipe
that is, the connection is down. But what’s wrong with my code?
It was exactly this problem, besides that when you create a variable in the if for some reason always comes 0. Thank you very much.
– Pedro Soares
it is not idiomatic to use identifiers starting with two underlines, these identifiers in principle are reserved for language implementation (Runtime, libraries, etc)
– zentrunix