Local communication using sockets

sockaddr_un

 

One way to communicate between processes is to use UNIX sockets, and people tend to use this way not with network sockets, but with something called local sockets. Doing so avoids leaving a backdoor for hackers.

Create
is created using the socket function socket, but the parameters passed are different from network sockets. The domain parameter should be PF_LOCAL or PF_UNIX, not PF_INET or the like. The communication type of the local socket should be SOCK_STREAM or SOCK_DGRAM, and the protocol is the default protocol. For example:
 int sockfd;
 sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);

Binding
Once a socket has been created, it must also be bound before it can be used. Unlike the binding of the network socket, the binding of the local socket is the struct sockaddr_un structure. The struct sockaddr_un structure has two parameters: sun_family, sun_path. sun_family can only be AF_LOCAL or AF_UNIX, and sun_path is the path to a local file. Usually files are placed in the /tmp directory. E.g:

 struct sockaddr_un sun;
 sun.sun_family = AF_LOCAL;
 strcpy(sun.sun_path, filepath);
 bind(sockfd, (struct sockaddr*)&sun, sizeof(sun));

Listening
and accepting connections on local sockets are similar to network sockets.

Before connecting
to a listening socket, you also need to fill in the struct sockaddr_un structure, and then call the connect function.

After the connection is established successfully, we can send and receive operations as if we were using network sockets. You can even set the connection to non-blocking mode, so I won't go into details here.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325435657&siteId=291194637