Kratos
Kratos

Reputation: 41

(linux)Socket returns 0

Though i know that 0 is a valid file descriptor in linux & can be returned by the call to socket(), but the subsequent call to bind or setsockopt fails with errorcode:88 (operation on non-socket). Also i am not able to understand where i might have closed my stdin file descriptor in order to get a socket value as 0. Here is my code snippet.. Its a simple socket class..

bool serverHandler::startServer(string strAddress,int port)
{
    //memset(&m_srvAddr,'\0',sizeof(m_srvAddr));
    m_srvSock = -1;
    if(m_srvSock = socket(AF_INET,SOCK_STREAM,0) < 0)
        cout<<"serverHandler: Failed to create server socket."<<endl;
    m_srvAddr.sin_family = AF_INET;
    m_srvAddr.sin_addr.s_addr = inet_addr(strAddress.c_str());                            
    m_srvAddr.sin_port = htons(port);
    cout<<"Socket value:"<<m_srvSock<<" for "<<strAddress<<" "<<port<<endl;
    if (bind(m_srvSock,(struct sockaddr *) &m_srvAddr,sizeof(m_srvAddr)) < 0)                     
    {
        cout<<"Failed with errno:"<<errno<<endl;
        return false;
    }
    if (listen(m_srvSock, MAX_PENDING) < 0)
    {
        return false;                
    }
}

And the call to this function is a simple:

srvHandler.startServer("127.0.0.1",7878);

I have used the same way to write down many socket programs, not getting what is wrong in this one.

Upvotes: 0

Views: 620

Answers (2)

Chris Merck
Chris Merck

Reputation: 454

I am not able to understand where i might have closed my stdin file descriptor in order to get a socket value as 0.

I just discovered how this was happening in a project of mine. Consider this situation:

int sock;

void init()
{
  sock = 0;
}

void start()
{
  sock = socket(...);
}

void cancel()
{
  close(sock);
}

This works fine so long as cancel is always called at most once per start, and you never have a call to init coming in-between.

In my case, an error handler was calling cancel after init had been called, which was causing close(0) and therefore closing stdin.

Upvotes: 0

Holt
Holt

Reputation: 37606

if(m_srvSock = socket(AF_INET,SOCK_STREAM,0) < 0)

Is not correct since < is evaluated before = (lower precedence), you need to add parenthesis:

if((m_srvSock = socket(AF_INET,SOCK_STREAM,0)) < 0)

If you're using GCC, you should set -W -Wall options to get warning for these kind of mistakes, with MVSC use at least /W4.

Upvotes: 1

Related Questions