简体   繁体   中英

socket bind() returns error EINVAL

I'm trying to bind the server socket so I can receive and listen for incoming messages from other clients. But I can't bind, it returns error - EINVAL (Invalid Argument). I have gone through the previously asked questions related to this error and Linux manual page says 'The socket is already bound to an address, and the protocol does not support binding to a new address; or the socket has been shut down.'

Here is the problematic server code in c:

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

#define LISTEN_BACKLOG 5

#define handle_error(msg) \
  do { perror(msg); exit(EXIT_FAILURE); } while(0)

int main(int argc, char* argv[])
{
  int sockfd, cfd;
  struct sockaddr_in myaddr, cl_addr;
  socklen_t cl_len;
  int quit = 0, reuse = 1;

  if (argc < 2)
  {
    fprintf(stderr, "ERROR, no port provided\n");
    exit(1);
  }

  if ((sockfd = socket(PF_LOCAL, SOCK_STREAM, 0)) == -1)
    handle_error("socket");

  printf("socket created.\n");

#ifdef SO_REUSEADDR
  if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
    perror("setsockopt(SO_REUSEADDR) failed");
#endif

#ifdef SO_REUSEPORT
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
        perror("setsockopt(SO_REUSEPORT) failed");
#endif

  memset(&myaddr, 0, sizeof(myaddr));
  myaddr.sin_family = AF_INET;
  myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  myaddr.sin_port = htons(atoi(argv[1]));

  printf("portno: %d\n", atoi(argv[1]));

  if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0)
    handle_error("bind");
  printf("bind successful\n");

  close(sockfd);
  unlink((const char *) &myaddr);

  return 0;
}

When I try to start the server, I get error EINVAL as shown below:

$ ./server 8032

socket created.

portno: 8032

bind: Invalid argument

Will be grateful to receive any inputs on this, thanks!

Problem is with the way you are creating socket.

 if ((sockfd = socket(PF_LOCAL, SOCK_STREAM, 0)) == -1)

Here you are creating socket for PF_LOCAL rather you want to create for AF_INET family.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM