Having the Client Request a Connection
At the top of your application, include vmci_sockets.h and declare a constant for buffer size. This does not have to be based on the size of a UDP datagram.
#include "vmci_sockets.h"
#define BUFSIZE 4096
To compile on Windows, you must call the Winsock WSAStartup() function. See Preparing the Server for a Connection for sample code.
Socket() Function
To alter a UDP socket program for VMCI sockets, obtain the new address family to replace AF_INET.
int afVMCI = VMCISock_GetAFValue();
if ((sockfd = socket(afVMCI, SOCK_DGRAM, 0)) == -1) {
perror("socket");
goto exit;
}
Sendto() Function
Because this is a connectionless protocol, you pass the socket address structure their_addr as a parameter to the sendto() call.
struct sockaddr_vm their_addr = {0};
their_addr.svm_family = afVMCI;
their_addr.svm_cid = SERVER_CID;
their_addr.svm_port = SERVER_PORT;
if ((numbytes = sendto(sockfd, buf, BUFIZE, 0,
(struct sockaddr *) &their_addr, sizeof their_addr)) == -1) {
perror("sendto");
goto close;
}
The sockaddr_vm structure contains an element for the CID to specify the virtual machine. For the client making a connection, the VMCISock_GetLocalCID() function returns the CID of the virtual machine.
The port number is arbitrary, although the server (listener) and client (connector) must use the same number, which must designate a port not already in use. Only privileged processes can use ports < 1024.
Connect() and Send()
Even with this connectionless protocol, applications can call the connect() function once to set the address, and call the send() function repeatedly without having to specify the sendto() address each time.
if ((connect(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr)) == -1) {
perror("connect");
goto close;
}
if ((numbytes = send(sockfd, send_buf, BUFSIZE, 0)) == -1) {
perror("send");
goto close;
}
Recvfrom() Function
The recvfrom() call optionally reads data from the server application. See Recvfrom() Function.
Close() Function
The close() call shuts down a connection, given the original socket descriptor obtained from the socket() function. To compile on Windows, call the Winsock closesocket(), as shown in Close() Function.