When using AF_UNIX
(unix domain sockets), is there any application to call bind()
in a process that never calls listen()
?
In my lecture on system and laboratory programming, we are tasked with bind()
invoking a unix domain socket on the client processes. Is there any documented, undocumented, or practical application for calling bind in a unix domain socket process for the client only? In my understanding, it bind()
creates a special socket file, which is responsible for the server process. Is it correct?
Here is a sample code based on what concepts are discussed in the 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"));
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;
}