Home > Software design >  Cannot create a tcp connection on linux in C
Cannot create a tcp connection on linux in C

Time:01-26

At first, here is my source code :

#include "server.h"
#include <netinet/in.h>
#include <unistd.h>
#include <thread>
#include <iostream>
#include <arpa/inet.h>
#include <sys/socket.h>

Server::Server(int port)
{
    m_Port = port;
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);


    sockaddr_in server_address;
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(port);
    server_address.sin_addr.s_addr = INADDR_ANY;

    bind(server_socket, (sockaddr *)&server_address, sizeof(server_address));

    listen(server_socket, SOMAXCONN);

    m_Socket = server_socket;
}

Server::~Server()
{
    close(m_Socket);
}

void Server::Process_Connection(const std::string message) const
{
    std::cout << message << "\n";
}

void Server::Start() const
{
    constexpr size_t BUFFER_SIZE = 4096;
    
    for (;;)
    {

        char buffer[BUFFER_SIZE] = "";

        sockaddr_in their_add;

        int connection = accept(this->m_Socket, (sockaddr *)&their_add, NULL);

        read(connection, buffer, 1024);

        std::cout << "Received: " << buffer << "\n";
        // std::cout << "Number of bytes read: " << val_read << "\n";

        std::thread temp(&Server::Process_Connection, this, buffer);
        temp.join();
    }
}

The problem is that in the line 57, the connection

int connection = accept(this->m_Socket, (sockaddr*)&their_add, NULL);

gets a value of -1, which is an invalid connection.

Do you have any suggestions? I'm quite new to the socket programming. Thank you in advance for your help

CodePudding user response:

Instead of this:

int connection = accept(this->m_Socket, (sockaddr*)&their_add, NULL);

This:

socklen_t size = sizeof(their_add);
int connection = accept(this->m_Socket, (sockaddr*)&their_add, &size);
  • Related