6

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; } 
1
  • Are you trying to pass an argument to main()? Commented Dec 6, 2013 at 19:30

1 Answer 1

6

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

@MZON Zeros is the same as INADDR_ANY. Your way is preferable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.