Solved

Error accepting connection, socket operation on non-socket.

Posted on 2010-09-20
6
731 Views
Last Modified: 2012-05-10
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

0
Comment
Question by:PDamasceno
  • 3
  • 3
6 Comments
 
LVL 35

Expert Comment

by:mccarl
ID: 33715774
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)
0
 

Author Comment

by:PDamasceno
ID: 33716073
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.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 33716182
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.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:PDamasceno
ID: 33716217
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

0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 33716309
You changed too much, that's not what I suggested. Try the following ...
bool Socket::Accept( Socket& socket )
{
   struct sockaddr_in address;
   int FD;

   socklen_t addrlen = sizeof( address );

   //Accept incoming connections
   FD = accept( m_socketFD, (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

0
 

Author Comment

by:PDamasceno
ID: 33716447
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.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now