Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind Invalid argument

I'm playing with the unix sockets. The code compiles fine but I get the following message on execute

Invalid argument

Here is the code i use. It's pretty simple I think

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

#define PORT 7000


int main(){
    int socket_desc;
    struct sockaddr_in address;

    socket_desc = socket(AF_INET, SOCK_STREAM, 0);

    if(socket_desc == -1)
        perror("Create socket");

    /* type of socket created in socket() */
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    /* set port */
    address.sin_port = htons(PORT);

    while(1) {
        /* bind the socket to the port specified above */
        if(bind(socket_desc,(struct sockaddr *)&address, sizeof(address)) < 0) {
            perror("Error");
            exit(-1);
        }
    }

    return 0;
}
like image 211
MZON Avatar asked Dec 06 '13 19:12

MZON


1 Answers

The problem is that you're trying to bind more than once -- what's with the while(1) loop?

while(1) {
    /* bind the socket to the port specified above */
    if(bind(socket_desc,(struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("Error");
        exit(-1);
    }
}

bind() succeeds the first time, and on the subsequent call it fails with EINVAL, which means (from man 2 bind):

[EINVAL] socket is already bound to an address and the protocol does not support binding to a new address. Alternatively, socket may have been shut down.

As a side note, it's probably a good idea to zero out the sockaddr prior to passing it in:

#include <string.h>
/* ... */

memset(&address, 0, sizeof(address));

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
like image 149
John Ledbetter Avatar answered Sep 25 '22 09:09

John Ledbetter