Solved

Error accepting connection, socket operation on non-socket.

Posted on 2010-09-20
6
744 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

813 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

12 Experts available now in Live!

Get 1:1 Help Now