Search code examples
csocketsbind

Invalid argument using bind() in C


This is the code that should create the socket and do the binding

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

#define SOCKNAME "./serverSC"

#define RETURNSYSCALL(r, c, e) if((r=c) == -1) {perror(e); exit(errno);}
#define SYSCALL(c, e) if(c == -1) {perror(e); exit(errno);}

void cleanup();

int main()
{
    cleanup();
    atexit(cleanup);

    int socketFd, socketComFd;
    struct sockaddr_un socketName;

    memset(&socketName, '0', sizeof(socketName));
    socketName.sun_family = AF_UNIX;
    strncpy(socketName.sun_path, SOCKNAME, strlen(SOCKNAME)+1);

    RETURNSYSCALL(socketFd, socket(AF_UNIX, SOCK_STREAM, 0), "Impossibile creare una socket");    
    SYSCALL(bind(socketFd, (struct sockaddr *) &socketName, sizeof(socketFd)), "Impossibile fare la bind");
    SYSCALL(listen(socketFd, 10), "Impossibile fare la listen");
    RETURNSYSCALL(socketComFd, accept(socketFd, NULL, 0), "impossibile fare la accept");

    return 0;
}

void cleanup() {
  unlink(SOCKNAME);
}

But the output it prints is:

Impossibile fare la bind: Invalid argument

some recommend using "AF_INET" instead of "AF_UNIX", but that doesn't work either.


Solution

  • The third argument of bind() is the size of address, so it should be sizeof(socketName), not sizeof(socketFd), in this case.