server.c
#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <myhead.h>
#include <unistd.h>
int main() {
int unix_socket = socket(AF_UNIX,SOCK_STREAM,0);
perror("");
struct sockaddr_un behS;
memset(&behS,0,sizeof(struct sockaddr_un));
behS.sun_family= AF_UNIX;
perror("");
strlcpy(behS.sun_path,"hello_c",1024);
perror("");
printf("%i\n",unix_socket);
perror("");
int wth = bind(unix_socket,
(struct sockaddr *)&behS,
sizeof(behS));
perror("");
return 0;
}
myhead.h
struct sockaddr_un {
short sun_family;
char sun_path[1024];
};
output
Success
Success
Success
3
Success
Invalid argument
the code is pretty straightforward why is it not working edit: I updated the code to what I have right now and fixed myhead.c to myhead.h (mistyped)
From the man page for bind
a possible error in the call bind(sockfd, const addr, addrlen)
is...
EINVAL addrlen is wrong, or addr is not a valid address for this socket's domain.
Your struct sockaddr_un
definition is...
struct sockaddr_un {
short sun_family;
char sun_path[1024];
};
Whereas the typical definition (again, from the relevant man page) will be something like...
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* Pathname */
};
That being the case, sizeof(behS)
in your own code will almost certainly not return the expected value and you get an EINVAL
.
The solution is to simply use the definition of struct sockaddr_un
provided in sys/un.h
.