0

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

4
  • 3
    When a system call returns an error, use perror() to see the error message. Commented Jan 25, 2023 at 20:18
  • 4
    I don't think you can pass addrlen=NULL when you pass a non-NULL addr argument. Commented Jan 25, 2023 at 20:20
  • 2
    Do you have any suggestions? Check the values returned from socket(), bind(), and listen() and make sure they didn't fail. Commented Jan 25, 2023 at 20:21
  • 1
    The return value from accept is a socket descriptor. You are going to need that descriptor (which you've assigned to the variable connection) to send something to the client. So connection needs to be given to the Process_Connection function. Commented Jan 28, 2023 at 20:43

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.