Chadi Helwe
Chadi Helwe

Reputation: 15

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;}

Upvotes: 1

Views: 1105

Answers (2)

Stian Skjelstad
Stian Skjelstad

Reputation: 2335

addr.sin_port = htonl((u_short)port);

should read

addr.sin_port = htons((u_short)port);

since port is 16bit number.

Upvotes: 0

Martin T&#246;rnwall
Martin T&#246;rnwall

Reputation: 9599

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.

Upvotes: 1

Related Questions