Link to home
Start Free TrialLog in
Avatar of PDamasceno
PDamascenoFlag for Canada

asked on

Error accepting connection, socket operation on non-socket.

Hey Experts.
I recenlty was writing the code to a small chat program on linux.
Finished with code but when I try to run it, I get this error from the accept funcion: socket operation on non-socket.
I looked everywhere for an answer with no luck.
Why this is happening and how can I get around this problem?
I'll show you the code to the Server, Client and Socket classes.
Thanks in advance.

Socket.cpp
#include "include/Socket.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include <string>
#include <iostream>

Socket::Socket( )
{
}

Socket::~Socket( )
{
}

void Socket::Listen( const int port )
{
   int yes = 1;
   struct sockaddr_in address;

   //Create socket and check if it worked
   if ( (m_socketFD = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
   {
      std::cerr << "Error creating socket :: " << strerror( errno ) << std::endl;
      return;
   }

   //Set socket to allow multiple connections
   if ( setsockopt(m_socketFD, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0 )
   {
      std::cerr << "Error setting socket option :: " << strerror( errno ) << std::endl;
      return;
   }

   address.sin_family = PF_INET;
   address.sin_addr.s_addr = INADDR_ANY;
   address.sin_port = htons( port );

   //Bind socket to the specified port
   if ( bind( m_socketFD, (struct sockaddr *)&address, sizeof( address )) < 0 )
   {
      std::cerr << "Error binding socket to port :: " << strerror( errno ) << std::endl;
      return;
   }

   //Listen for connection calls
   if ( listen( m_socketFD, 20 ) < 0 )
   {
      std::cerr << "Error listening for connections :: " << strerror( errno ) << std::endl;
      return;
   }
}

void Socket::Connect( const char *hostname, const int port )
{
   struct sockaddr_in address;

   //Create socket and check if it worked
   if ( (m_socketFD = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
   {
      std::cerr << "Error creating socket :: " << strerror( errno ) << std::endl;
      return;
   }

   address.sin_family = PF_INET;
   address.sin_port = htons( port );
   address.sin_addr.s_addr = inet_addr( hostname );

   if ( connect( m_socketFD, (struct sockaddr *)&address, sizeof( address )) < 0 )
   {
      std::cerr << "Error connecting to server :: " << strerror( errno ) << std::endl;
      return;
   }
}

bool Socket::Accept( Socket& socket )
{
   struct sockaddr_in address;
   int FD;

   socklen_t addrlen = sizeof( address );

   //Accept incoming connections
   if ( FD = accept( m_socketFD, (struct sockaddr *)&address, &addrlen ) < 0 )
   {
      std::cerr << "Error accepting connection :: " << strerror( errno ) << std::endl;
      return false;
   }

   m_socketFD = FD;
   return true;
}

void Socket::Close( )
{
   //Close socket
   if ( close( m_socketFD ) < 0 )
   {
      std::cerr << "Error closing socket :: " << strerror( errno ) << std::endl;
      return;
   }
}

int Socket::SendData( std::string packedMessage )
{
   std::string *message = &packedMessage;
   int nbytes;

   //Send packed message to socket
   if ( nbytes = send( m_socketFD, message, sizeof( message ), 0) <= 0 )
   {
      std::cerr << "Error sending to socket :: " << strerror( errno ) << std::endl;
      return -1;
   }

   return 1;
}

int Socket::RecvData( char *buffer )
{
   int nbytes;

   //Get packed message from socket
   if ( nbytes = recv( m_socketFD, buffer, sizeof( buffer ) - 1, 0 ) <= 0 )
   {
      if ( nbytes == 0 )
      {
         std::cerr << "Client closed the connection." << std::endl;
      }
      else
      {
         std::cerr << "Error receiving from socket :: " << strerror( errno ) << std::endl;
      }
      return -1;
   }

   return 1;
}

int Socket::DataCheck( )
{
   fd_set readfds;
   int retval;

   FD_ZERO( &readfds );
   FD_SET( m_socketFD, &readfds );

   retval = select ( m_socketFD + 1, &readfds, NULL, NULL, NULL );

   return retval;
}

Open in new window


Server.cpp
#include "include/Server.h"
#include "include/Socket.h"
#include "include/ServerDispatcher.h"
#include "include/ClientHandler.h"
#include <exception>
#include <iostream>

const int port = 9000;

Server::Server( )
{
}

Server::~Server( )
{
}

int main( )
{
   ServerDispatcher& serverDispatcher = ServerDispatcher::Instance( );

   Socket serverSocket;
   serverSocket.Listen( port );

   for ( ;; )
   {
      Socket dataSocket;
      if ( serverSocket.Accept( dataSocket ) == true )
      {
         ClientHandler* clientHandler = new ClientHandler( dataSocket );
         serverDispatcher.AddClient( clientHandler );
         std::cout << "A client connected to the server.";
      }

      if ( serverDispatcher.IsClientListEmpty( ) )
      {
         break;
      }
   }

   serverSocket.Close ( );
   return 0;
}

Open in new window


Client.cpp
#include "include/ChatMessage.h"
#include "include/AttentionMessage.h"
#include "include/ServerMessage.h"
#include "include/Client.h"
#include "include/Socket.h"
#include "include/Sender.h"
#include <string>
#include <iostream>

const int port = 9000;
const char hostname[] = "127.0.0.1";

Client::Client( )
{
}

Client::~Client( )
{
}

void Client::SetUsername( std::string username )
{
   m_username = username;
}

std::string Client::GetUsername( )
{
   return m_username;
}

int main( )
{
   char buffer[1024];
   std::string usr;
   std::string packedMessage;
   size_t result;
   Client client;

   std::cout << "Client/Server Chat" << std::endl;
   std::cout << "Digite o nome de usuário: ";
   std::getline( std::cin, usr );
   client.SetUsername( usr );

   Socket clientSocket;
   clientSocket.Connect( hostname, port );
   Sender msgSender = Sender( clientSocket );

   while ( true )
   {
      if ( clientSocket.DataCheck( ) > 0 )
      {
         try
         {
            clientSocket.RecvData( buffer );
            packedMessage = buffer;
            result = packedMessage.find_first_of( "CM" );
            if ( result != std::string::npos && result < 3 )
            {
               ChatMessage msg;
               msg.Unpack( packedMessage );
               std::cout << "[" << msg.GetTime( ) << "] " << msg.GetUsername( ) << ": " << msg.GetMessage( ) << std::endl;
            }

            result = packedMessage.find_first_of( "AT" );
            if ( result != std::string::npos && result < 3 )
            {
               AttentionMessage attmsg;
               attmsg.Unpack( packedMessage );
               std::cout << "[" << attmsg.GetTime( ) << "] " << attmsg.GetUsername( ) << " is asking for the ATTENTION of all chat members!!!" << std::endl;
            }

            result = packedMessage.find_first_of( "SM" );
            if ( result != std::string::npos && result < 3 )
            {
               ServerMessage smsg;
               smsg.Unpack( packedMessage );
               std::cout << "[" << smsg.GetTime( ) << "] " << "SERVER: " << smsg.GetUsername( ) << " has logged in." << std::endl;
            }
         }
         catch ( std::exception &e )
         {
            break;
         }
      }
   }

   clientSocket.Close( );
   return 0;
}

Open in new window

Avatar of mccarl
mccarl
Flag of Australia image

Does it work up until the first client connects, and then gives the error?

Line 94 of Socket.cpp is incorrent. You are overwriting the FD of the server's listening socket with that of the incoming client socket. You are also not doing anything with the Socket object that you are passing into the Accept method. Maybe line 94 should be something like...

socket.m_socketFD = FD;

Although you may have to sort out public/private issues with this. You may need to provide a way to set the FD on your Socket objects. (And whatever associated management of your Socket objects properties that that may entail)
Avatar of PDamasceno

ASKER

I start the server and it keeps listening for connections.
I only get the error when I start a client and the server try to accept the connection of the client.
Do you see the message on stdout (from line 32 : Server.cpp) "A client connected to the server." and then the error on stderr (from line 90 : Socket.cpp) "Error accepting connection :: ..." ? If so, then I think the problem is as I stated above. You're accept function is working correctly the first time through but then as soon as the client connects, you are overwriting your reference to the server sockets FD and then when your server goes through the loop to call accept again you are getting the error message.
No, the server show the error on the first try to accept a connection.
I added a get and set functions to the socket class to change the variable m_socketFD, since it is private. But now the server doesn't even wait for a connection, I run ./Server and it just shows me that error, socket operation on non-socket, and exits.

The code with my alterations is attached.

bool Socket::Accept( Socket& socket )
{
   struct sockaddr_in address;
   int clientFD = socket.GetSocketFD( );
   int FD;

   socklen_t addrlen = sizeof( address );

   //Accept incoming connections
   FD = accept( clientFD, (struct sockaddr *)&address, &addrlen );
   if ( FD < 0 )
   {
      std::cerr << "Error accepting connection :: " << strerror( errno ) << std::endl;
      return false;
   }

   socket.SetSocketFD( FD );
   return true;
}

int Socket::GetSocketFD( )
{
   return m_socketFD;
}

void Socket::SetSocketFD( int FD )
{
   m_socketFD = FD;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Did what you told in the last post and there is no erros anymore.
Thanks.

I'm having problens sending messages between clients though.
But I'll save it for other question if I can't get around it on my own.