1

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;}
1
  • If you get an error, (a) don't just print some message of your own devising: use perror() or strerror(), and (b) don't continue as though the error didn't happen. And it isn't correct to test system calls for != 0: the correct test is == -1 or < 0. Commented Feb 26, 2015 at 23:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

should read

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

since port is 16bit number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.