Shyvert
Shyvert

Reputation: 27

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.

Upvotes: 0

Views: 1102

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

memset(&socketName, '0', sizeof(socketName));

'0' makes no sense whatsoever. Use 0 (no quotation marks).

strncpy(socketName.sun_path, SOCKNAME, strlen(SOCKNAME)+1);

The size parameter of the strncpy is meant to be the size of the destination buffer, not the source string. The latter is completely and utterly useless. If you want to copy the entire source string, just use strcpy, it does exactly that. Moreover, strncpy is a dangerous function that should be used with caution. It does not necessarily null-terminate the target buffer, and people tend to forget about that. If you insist, do it this way:

strncpy (socketName.sun_path, SOCKNAME, sizeof(socketName.sun_path));
socketName.sun_path[sizeof(socketName.sun_path) - 1] = 0;

Finally, sizeof(socketFd) should be sizeof(socketName).

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

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

Upvotes: 3

Related Questions