When using AF_UNIX
(unix domain sockets), is there any application to calling bind()
in a process that never calls listen()
?
In my systems programming lecture and lab, we are instructed to callbind()
on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket process? From my understanding bind()
creates the special socket file, which is a responsibility a server process would undertake. Is this correct?
Here is an example code based off of what concepts discussed in class:
server.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int main() {
int s0, s1;
struct sockaddr sa0 = {AF_UNIX, "a"};
s0 = socket(AF_UNIX, SOCK_STREAM, 0);
bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
listen(s0, 1);
for (;;) {
s1 = accept(s0, NULL, NULL);
puts("connected!");
for (;;) {
char text[1];
ssize_t n = read(s1, &text, sizeof(text));
if (n < 1) {
break;
}
putchar(text[0]);
}
close(s1);
}
close(s0);
unlink("a");
return 0;
}
client.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int main() {
int s0;
struct sockaddr sa0 = {AF_UNIX, "b"};
struct sockaddr sa1 = {AF_UNIX, "a"};
socklen_t sa1_len;
s0 = socket(AF_UNIX, SOCK_STREAM, 0);
bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
for (;;) {
int c = fgetc(stdin);
if (c == EOF) {
break;
}
write(s0, &c, sizeof(c));
}
close(s0);
unlink("b");
return 0;
}
bind
call in the client does anything useful, but I could have forgotten something, which is why this is not an answer. It is definitely not necessary, which you can observe for yourself by removing it from the client program. – Bystanderb
, if I delete it during runtime, the server still reads the client okay. And it works without thebind()
in client. – Eirene