Bind failed: address already in use with SO_REUSEADDR

47 Views Asked by At

I am building the socket part of a project I am working on and I keep getting bind failed: address already in use. I tried to use SO_REUSEADDR too but it doesn't seem to solve it. How do I fix this?

EDIT: For anyone getting my problem while testing, there's a file that gets generated in your folder named as the socket name. Delete it and you can keep testing.

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <string.h>

#define SOCKNAME "farm.sck"

typedef struct sockaddr Sockaddr_t;

int bind_check(int* sfd, Sockaddr_t* sa){
    if((bind(*sfd,sa,sizeof(sa)))==-1){
        perror("bind_check");
        return -1;
    }
    else puts("bind done");
    return 0;
    
}

int main(int argc, char* argv[]){
   
   int sock_fd;

   struct sockaddr_un sa;     
   strncpy(sa.sun_path, SOCKNAME, strlen(SOCKNAME)+1);
   sa.sun_family= AF_LOCAL;
   sock_fd = socket(AF_LOCAL, SOCK_STREAM, 0);

   if(sock_fd == -1){
      perror("socket_create");
      exit(EXIT_FAILURE);
   }
   int o = 1;
   if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &o, sizeof(int)) < 0){
      perror("setsockopt(SO_REUSEADDR) failed");
      exit(EXIT_FAILURE);
   }
   if(bind_check(&sock_fd, (Sockaddr_t*)&sa) == -1) exit(EXIT_FAILURE);

   puts("OK");
   //[...] 
}
   

This is the output:

bind_check: Address already in use

I have no clue of what I'm doing wrong

0

There are 0 best solutions below