Search code examples
c++csocketsnetwork-programmingbsd

Socket API :Socket operation on non-socket


Hello I have a problem when I am writing the server using the socket api. I always get this error: "Socket operation on non-socket"

struct sockaddr_in addr;
int port = 10000;
int sd;

memset((char *) &addr,0, sizeof(addr));
addr.sin_family = PF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htonl((u_short)port);

if ((sd = socket(PF_INET, SOCK_STREAM, 0) < 0)) {

    printf("socket failed");
}

if(bind(sd, (struct sockaddr *)&addr, sizeof(addr)) != 0)
{
    printf(strerror(errno));
}

close(sd);


return 0;}

Solution

  • The line:

    if ((sd = socket(PF_INET, SOCK_STREAM, 0) < 0)) {
    

    Doesn't do what you think. If you look closely at the placement of parentheses (and remember that the < operator has higher priority than =) you will notice that you are actually assigning sd the value of the expression socket(PF_INET, SOCK_STREAM, 0) < 0.

    In short, sd will most likely end up containing the value 0, because that's what the above expression would normally evaluate to. This explains the "socket operation on non-socket" error; it really isn't a socket.

    So the line should read:

    if ((sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
    

    Notice how I shifted a closing parenthesis left by two tokens.