Analysis of UNIX domain socket

Time:2021-5-5

unix domain socket

UNIX domain socket is developed on the socket architecture, which is used for inter process communication (IPC) of the same host. It does not need to go through the network protocol stack, package and unpack, calculate the check sum, maintain the serial number and reply, and just copies the application layer data from one process to another. UNIX domain socket has sock_ Dgram or sock_ Stream has two working modes, similar to UDP and TCP, but UNIX domain socket for message is also reliable, and messages will not be lost or disordered.

UNIX domain socket can be used for two unrelated processes. It is full duplex and is the most widely used IPC mechanism. For example, the communication between X window server and GUI program is through UNIX domain socket.

UNIX domain socket is similar to network socket, and can be compared with network socket.

The differences between the two programs are as follows:

  • Address family is AF_ UNIX
  • Because it is used in IPC, unixdomain socket does not need IP and port, instead, it uses file path to represent “network address”. This is reflected in the following two aspects.
  • Unixdomain socket uses the structure SOCKADDR_ UN indicates the path of a socket type file in the file system. The socket file is created by calling bind(). If the file already exists when calling bind(), the bind() error returns.
  • UNIX domain socket client usually calls bind function explicitly, but does not rely on the address automatically assigned by the system like network socket. The socket file name of the client bind can contain the client’s PID, so that the server can distinguish different clients.

The following demonstrates the use of UDS with Python code

Python code demonstration

Server

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Created on 12/11/17 11:55 AM
@author: Chen Liang
@function: socket_echo_server_uds
"""

import sys

reload(sys)
sys.setdefaultencoding('utf-8')
import socket
import os

server_address = './uds_socket'

# Make sure the socket does not already exist
try:
    os.unlink(server_address)
except OSError:
    if os.path.exists(server_address):
        raise

# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

# Bind the socket to the address
print('starting up on {}'.format(server_address))
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print('waiting for a connection')
    connection, client_address = sock.accept()
    try:
        print('connection from', client_address)

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print('received {!r}'.format(data))
            if data:
                print('sending data back to the client')
                connection.sendall(data)
            else:
                print('no data from', client_address)
                break

    finally:
        # Clean up the connection
        connection.close()

client

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Created on 12/11/17 11:55 AM
@author: Chen Liang
@function: socket_echo_client_uds
"""

import sys

reload(sys)
sys.setdefaultencoding('utf-8')


import socket
import sys

# Create a UDS socket
sock = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = './uds_socket'
print('connecting to {}'.format(server_address))
try:
    sock.connect(server_address)
except socket.error as msg:
    print(msg)
    sys.exit(1)

try:

    # Send data
    message = b'This is the message.  It will be repeated.'
    print('sending {!r}'.format(message))
    sock.sendall(message)

    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print('received {!r}'.format(data))

finally:
    print('closing socket')
    sock.close()

The client sends it once, and the server returns it in batches.

The output of the server is as follows

[email protected]:~/PycharmProjects/python_scripts# python socket_echo_server_uds.py 
starting up on ./uds_socket
waiting for a connection
('connection from', '')
received 'This is the mess'
sending data back to the client
received 'age.  It will be'
sending data back to the client
received ' repeated.'
sending data back to the client
received ''
('no data from', '')
waiting for a connection

The client output is as follows

[email protected]:~/PycharmProjects/python_scripts# python socket_echo_client_uds.py 
connecting to ./uds_socket
sending 'This is the message.  It will be repeated.'
received 'This is the mess'
received 'age.  It will be'
received ' repeated.'
closing socket

The types of socket files are as follows

[email protected]:~/PycharmProjects/python_scripts# ls -l ./uds_socket
srwxr-xr-x 1 root root 0 Dec 11 13:45 ./uds_socket

soUDS file is socket type. Specific Linux file types are as follows:

Linux has the following file types:

file type ls -ldisplay
General document -
catalogue d
Symbolic links l
Character device c
Block device b
socket s
name pipes p

reference resources:


Remember to praise me!

We have carefully arranged video courses and e-books from entry-level, advanced and practical in all directions of computer. We can always find the learning materials you need according to the reasonable classification of the catalogue. What are you waiting for? Pay attention to download it!!!

resource-introduce

If you don’t forget, there will be an echo. Please give me a compliment. Thank you very much.

I am a bright brother in the workplace, YY Senior Software Engineer, with four years of working experience. I refuse to be a leading slash programmer.

Listen to me, more progress, a shuttle of procedural life

If you are lucky enough to help you, please give me a “like” to pay attention to it. If you can comment on it and give me encouragement, I will be very grateful.

List of articles of workplace bright brother:More articles

wechat-platform-guide-attention

All my articles and answers have cooperation with the copyright protection platform. The copyright belongs to brother Liang in the workplace. Without authorization, reprint must be investigated!