stream_socket = socket(AF_VSOCK, SOCK_STREAM, 0);
datagram_socket = socket(AF_VSOCK, SOCK_DGRAM, 0);
Valid socket types are SOCK_STREAM and SOCK_DGRAM. SOCK_STREAM provides connection-oriented byte streams with guaranteed, in-order delivery. SOCK_DGRAM provides a connectionless datagram packet service with best-effort delivery and best-effort ordering. Availability of these socket types is dependent on the underlying hypervisor.
A new socket is created with
socket(AF_VSOCK, socket_type, 0);
When a process wants to establish a connection, it calls connect(2) with a given destination socket address. The socket is automatically bound to a free port if unbound.
A process can listen for incoming connections by first binding to a socket address using bind(2) and then calling listen(2).
Data is transmitted using the send(2) or write(2) families of system calls and data is received using the recv(2) or read(2) families of system calls.
struct sockaddr_vm {
sa_family_t svm_family; /* Address family: AF_VSOCK */
unsigned short svm_reserved1;
unsigned int svm_port; /* Port # in host byte order */
unsigned int svm_cid; /* Address in host byte order */
unsigned char svm_zero[sizeof(struct sockaddr) -
sizeof(sa_family_t) -
sizeof(unsigned short) -
sizeof(unsigned int) -
sizeof(unsigned int)];
};
svm_family is always set to AF_VSOCK. svm_reserved1 is always set to 0. svm_port contains the port number in host byte order. The port numbers below 1024 are called privileged ports. Only a process with the CAP_NET_BIND_SERVICE capability may bind(2) to these port numbers. svm_zero must be zero-filled.
There are several special addresses: VMADDR_CID_ANY (-1U) means any address for binding; VMADDR_CID_HYPERVISOR (0) is reserved for services built into the hypervisor; VMADDR_CID_LOCAL (1) is the well-known address for local communication (loopback); VMADDR_CID_HOST (2) is the well-known address of the host.
The special constant VMADDR_PORT_ANY (-1U) means any port number for binding.
The local CID may change across live migration if the old CID is not available on the new host. Bound sockets are automatically updated to the new CID.
The local CID obtained with IOCTL_VM_SOCKETS_GET_LOCAL_CID can be used for the same purpose, but it is preferable to use VMADDR_CID_LOCAL .
VMADDR_CID_LOCAL is supported since Linux 5.6. Local communication in the guest and on the host is available since Linux 5.6. Previous versions supported only local communication within a guest (not on the host), and with only some transports (VMCI and virtio).