Prithvi Raj
Prithvi Raj

Reputation: 1961

socket programming , bind() error

My code which I have written for server implementation is not working. program cant bind() socket address properly and generate error.

Code

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include <netdb.h>

int main(int argc , char* argv[])
{
    int socket_descriptor;
    struct sockaddr_in server;
    char buffer[512];
    int rval;
    int socket_a;

    if(socket_descriptor = socket(AF_INET, SOCK_STREAM , 0) < 0)
    {
        perror("Error at creating the socket");
        exit(1);
    }

    server.sin_family  = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(5000);

    if(bind(socket_descriptor,(struct sockaddr * )&server,sizeof(server)) < 0)
    {
        perror("Error at binding");
        exit(1);
    }

}

Error

Error at binding: Socket operation on non-socket .

Upvotes: 2

Views: 1384

Answers (1)

dbush
dbush

Reputation: 223689

Here's your problem:

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

The less-than operator < has higher precedence than the assignment operator =. So the above is equivalent to:

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

Assuming socket succeeds, the file descriptor returned will not be negative, so the comparison will evaluate to 0 (i.e. false) and that value is then assigned to socket_descriptor. And since file descriptor 0 is stdin, you get the error about a socket operation on a non-socket.

Adding the proper set of parenthesis will assign the socket to socket_descriptor:

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

Upvotes: 6

Related Questions