Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot create a tcp connection on linux in C++

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading