Win*_*nny 6 c unix sockets system
使用AF_UNIX
(unix域套接字)时,是否有任何应用程序可以bind()
在永不调用的进程中进行调用listen()
?
在我的系统编程课程和实验中,我们被要求调用bind()
Unix域套接字客户端进程。是否有任何已记录,未记录或实际的应用程序可以在仅客户端的 UNIX域套接字 进程上调用bind ?据我了解,bind()
创建了一个特殊的套接字文件,这是服务器进程要承担的责任。它是否正确?
这是一个基于类讨论的概念的示例代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
man bind
给出了这个答案:
When a socket is created with socket(2), it exists in a name space\n (address family) but has no address assigned to it. bind() assigns the\n address specified by addr to the socket referred to by the file\n descriptor sockfd. addrlen specifies the size, in bytes, of the\n address structure pointed to by addr. Traditionally, this operation is\n called \xe2\x80\x9cassigning a name to a socket\xe2\x80\x9d.\n\n It is normally necessary to assign a local address using bind() before\n a SOCK_STREAM socket may receive connections (see accept(2)).\n
Run Code Online (Sandbox Code Playgroud)\n