CITS3002 Computer Networks  
prev
next CITS3002 help3002 CITS3002 schedule  

A Client Process in the Unix Domain (in C)

Consider a simple client process wishing to establish a connection with a server process in the Unix domain. When communicating within the Unix domain, the data frames never leave the single computer, and never get lost (other than on an extremely busy machine).

In this example, the client program sends commands to a 3D printer which is directly connected to the same computer. The client process simply connects to the server process and then writes the bytes to be printed to the socket (note that this example is far from how print spooling works in practice!)

#include <many-header-files.h>

int write_file_to_server(int sd, const char filenm[])
{
//  ENSURE THAT WE CAN OPEN PROVIDED FILE
    int fd  = open(filenm, O_RDWR, 0);

    if(fd >= 0) {
        char  buffer[1024];
        int   nbytes;

//  COPY BYTES FROM FILE-DESCRIPTOR TO SOCKET-DESCRIPTOR
        while( (nbytes = read(fd, buffer, sizeof(buffer) ) ) {
            if(write(sd, buffer, nbytes) != nbytes) {
                close(fd);
                return 1;
            }
        }
        close(fd);
        return 0;
    }
    return 1;
}

int main(int argc, char *argv[])
{
//  ASK OUR OS KERNEL TO ALLOCATE RESOURCES FOR A SOCKET
    int sd = socket(AF_UNIX, SOCK_STREAM, 0);
    if(sd < 0) {
        perror(argv[0]);     // issue a standard error message
        exit(EXIT_FAILURE);
    }

//  FIND AND CONNECT TO THE SERVICE ADVERTISED WITH "THREEDsocket"
    if(connect(sd,"THREEDsocket",strlen("THREEDsocket")) == -1) {    
        perror(argv[0]);     // issue a standard error message
        exit(EXIT_FAILURE);
    }
    write_file_to_server(sd, FILENM_OF_COMMANDS);
    shutdown(sd, SHUT_RDWR);
    close(sd);
    exit(EXIT_SUCCESS);
}




CITS3002 Computer Networks, Lecture 8, Transport layer protocols and APIs, p15, 24th April 2024.