0% found this document useful (0 votes)
4 views151 pages

Computer Networks & Linux Admin Guide

Network and linux adminstration

Uploaded by

Anjana VP
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views151 pages

Computer Networks & Linux Admin Guide

Network and linux adminstration

Uploaded by

Anjana VP
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER NETWORK AND

LINUX ADMINISTRATION
MCA S1 23-24
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION

References:
● Data Communications and networking, Fourth Edition by Behrouz A. Forouzan, McGraw
Hill 2017
● Computer Networks, Fifth Edition by Andrew S. Tanenbaum, Prentice-Hall 2011
● Data and computer communication, Tenth Edition by William Stallings, Prentice-Hall 2014
● Evi Nemeth , et al, Linux Administration Hand Book , PHI 2018
● Nicholas Wells, Linux Installation and Administration, Thomson Vikas 2003.
● Olaf Kirch& Terry Dawson, Linux Network Administrators Guide, O’relly, 2003
● Hunt, Linux DNS server Administration, BPB Publication, 2003
● W Richard Stevens, Unix Network Programming, PHI, 2002
● Linux AdministrationA Beginner’s Guide, Wale Soyinka , 7th Edition.

Department of Information Technology, Kannur University


Concepts of Data Interprocess Communication
Communications &
Networks

Unit I Unit II Unit III Unit IV

Linux Administration Network Configuration

Department of Computer Science, Farook College (Autono


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION

Unit 3

Inter Process Communication programming : Create a process- fork() system


call, Parent and Child Process, Process ID, User and Group ID, Half Duplex Unix
Pipes, Named Pipes, (First In First Out), Streams and messages, System V IPC
:Message Queues, Semaphores, Shared memory, Sample programs for IPC
that uses Pipes, FIFO; Socket Programming: Overview, socket address,
Elementary Socket System Calls: socket, socket pair, bind, connect, listen,
accept, send, sendto, recv, recvfrom, close, Byte ordering routines, Byte
Operations, Address conversion routines, Simple client Programs that uses
some reserved ports, Simple Client / Server Program using unreserved ports.

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION

Inter Process Communication (IPC)

● IPC is a facility offered by the operating system to assist processes that are
running concurrently to communicate with each other
● IPC can occur between the child processes of a parent process and
between processes that are not related to each other
● IPC ensures both communication and synchronization between the
participating processes

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION

Inter Process Communication (IPC)

● The Linux supports IPC several methods


of IPC
○ Half-duplex UNIX pipes
○ FIFOs (named pipes)
○ SYSV style message queues
○ SYSV style semaphore sets
○ SYSV style shared memory segments
○ Semaphores
○ Networking sockets (Berkeley style)
○ Full-duplex pipes (STREAMS pipes)

Department of Information Technology, Kannur University

MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION

Inter Process Communication (IPC)


- Half-duplex UNIX pipes
● The eldest of the IPC tools used for IPC
● Even used in the early versions of the UNIX operating system
● Provide a method of one-way communications (hence the term
half-duplex) between processes
● A method of connecting the standard output of one process to the
standard input of another
● Available in shell commands
○ ls | sort
○ Here the output of ls command is fed as the input to the sort
command

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Pipes are unidirectional
○ one end must be designated as the reading end and the other as the
writing end
● Pipes are order preserving
○ All data read from the receiving end of the pipe will match the order
in which it was written into the pipe
● Pipes have a limited capacity and they use asynchronous send and
blocking receive operations
○ If a pipe is full, process wishing to write the pipe will be blocked until
some of the data has been read
○ The writing process has no control over when the bytes will be
removed from the pipe.

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION

Inter Process Communication (IPC)


- Half-duplex UNIX pipes
● Pipes send data as unstructured byte streams
○ There are no pre-defined characteristics to the data exchanged, such
as a predictable message length
○ The processes using the pipe must agree on a communication
protocol and handle errors appropriately (such as if one of the
processes terminates the communication early)

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● How a pipe is designed?
● As we have noted, a pipe has two ends
○ A read end through which a process can read the data
○ A write end using which a process can write data to the pipe
● When a process creates a pipe, the kernel sets up two file descriptors for
use by the pipe
○ One descriptor is used to allow a path of input into the pipe (write)
○ The other is used to obtain data from the pipe (read)

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Even if a pipe is created for a process, the data flow of the pipe occurs
through the kernel

● Once the pipe is created for a process, it can be used for communicating
with itself!
● How does the pipe can be shared with another process?

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● How does the pipe can be shared with another process?
● A child process can be forked so that the pipe created for the parent can
be shared with the child!
● The child process will inherit all the file descriptors that are opened by the
parent
● Now the pipe is open for communication!

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Now the pipe is open for communication!
● At this stage, that a critical decision must be made!
○ In which direction the data should travel?
○ Does the child process send information to the parent, or vice versa?

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Parent and child will have a mutual agreement about this
● They will assume their roles as sender and receiver
● Sender will close the read end of the pipe and the receiver will close the
write end of the pipe!
● This will keep ready the pipe for communication !

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● How to create a pipe?
○ pipe() system call
○ Syntax: int pipe(int fd[2]);
○ Creates a simple pipe
○ An integer array of two elements is passed as the argument to this
function
○ The first element of the array (fd[0]) is a file pointer to the read end of
the pipe
○ The second element of the array (fd[1]) is a file pointer to the write
end of the pipe
○ Return value: 0 on success, -1 on error
○ Header files required: stdio.h, unistd.h, sys/types.h

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● How to create a pipe?#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
int r;
int buffer[2];

printf("\nDemonstration of IPC using Pipe");

// Create Pipe
r = pipe(buffer);
if (r== -1) {
printf("\nPipe could not be created!");
return 1;
}

printf("\nPipe created for the Parent Process!");


return 0;
}
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Use the pipe for communication!
#include <stdio.h> /* Write data through the output side
#include <unistd.h> of pipe */
#include <sys/types.h> printf("\nData being sent to the Pipe:
IPC using PIPE!");
int main() {
int i, r; r = write(buffer[1], "IPC using PIPE!",
15);
int buffer[2];
pid_t pid;
char c_data[20]; if (r== -1) {
printf("\nPipe: Data could not be
printf("\nDemonstration of IPC using send!");
Pipe"); return 1;
}
// Create Pipe
r = pipe(buffer);
if (r== -1) {
printf("\nPipe could not be
created!");
return 1;
Department of Information Technology, Kannur University
}
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Use the pipe for communication!
#include <stdio.h> /* Write data through the output side
#include <unistd.h> of pipe */
#include <sys/types.h> printf("\nData being sent to the Pipe:
IPC using PIPE!");
int main() {
int i, r; r = write(buffer[1], "IPC using PIPE!",
15);
int buffer[2];
pid_t pid;
char c_data[20]; if (r== -1) {
printf("\nPipe: Data could not be
printf("\nDemonstration of IPC using send!");
Pipe"); return 1;
}
// Create Pipe
r = pipe(buffer);
if (r== -1) {
printf("\nPipe could not be
created!");
return 1;
Department of Information Technology, Kannur University
}
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Use the pipe for communication!
/* Read data through the input side
of pipe */
r = read(buffer[0], c_data,
sizeof(c_data));

if (r== -1) {
printf("\nPipe: Data could not be
read!");
return 1;
}

printf("\nData Read from Pipe: %s", ● Here the owner of the pipe itself
c_data); uses the pipe for data transfer

close(buffer[0]); ● Pipe has a meaning when we use


close(buffer[1]); it for transferring data to another
process!
return 0;

} Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Pipe for IPC
#include <stdio.h> //create a child process
#include <unistd.h> pid = fork();
#include <sys/types.h>

int main() {
int r; return 0;
int buffer[2]; }
Pid_t pid; ● Now the pipe is to be configured for
data transfer!
● Let the child process be the sender - it
printf("\nDemonstration of IPC using Pipe");
will send few bytes to the pipe
// Create Pipe
● Parent will read the data sent by the
r = pipe(buffer); child from the pipe!
if (r== -1) {
printf("\nPipe could not be created!");
return 1;
}

printf("\nPipe created for the Parent Process!");


Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Pipe for IPC
pid = fork();
if (pid == -1) {
printf("\nChild process could not be created!");
● Child closes the read end of the pipe return 1;
}
● Sends data through the write end of
the pipe!
//printf("\n%d", pid);
if(pid == 0) {
/* Child process closes up read side of pipe */
close(buffer[0]);
/* Send data through the output side of pipe */

r = write(buffer[1], "IPC using PIPE!", 15);

if (r== -1) {
printf("\nPipe: Data could not be send!");
return 1;
}
printf("\nChild Process: Data is sent to the
pipe!");
}
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Pipe for IPC
/* Parent process closes up write side of pipe */
close(buffer[1]);
/* Read data through the input side of pipe */
● Parent closes the write end of the pipe
r = read(buffer[0], c_data, 15);
● Reads data through the read end of
the pipe!
if (r== -1) {
printf("\nPipe: Data could not be send!");
return 1;
}
printf("\nParent Process: Data read from the
pipe: %s", c_data);

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Steps

1. Parent creates pipe


2. Parent forks the child process
pid = fork()
3. If pid == 0)
a. Child closes read end of the pipe
b. Child writes the data to the pipe

else
c. Parent closes its writeend of the pipe
d. Parent reads the message written by the child from
the pipe
e. Parent echos the data to standard output
4. Stop

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● How to create “two way” pipes?
1. Parent creates pipe1 for the Parent to write
2. Parent creates pipe2 for the Child to write
3. Parent creates the child
4. pid = fork()
5. If (pid != 0)
a. Parent closes the read end of pipe1 and the write end of pipe2
b. Parent sends a message to the child in pipe1
c. Parent reads and displays the message from the child in pipe 2
d. Parent closes the write end of pipe1 and the read end of pipe2
e. Wait for the child process to execute
6. else
a. Child closes the write end of pipe1 and the read end of pipe2
b. Child sends a message to the parent in pipe2
c. Child reads and displays the message from the parent in pipe 1
d. Child closes the write end of pipe2 and the read end of pipe1

7. Stop

See pipe3.c
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Point to Ponder

● A pipe is to be explicitly created for a process


● Pipe is created for the process by the Kernel
● When the owner of the pipe accesses the pipe its as good as a local variable
● But still
○ A local variable is created by the process in its own address space
○ It can be accessed and its value can be modified by the owner process without
the intervention of the Kernel
○ But for all activities related to the pipe is channel through the Kernel - its creation,
read, write and close operations

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Half-duplex UNIX pipes
● Point to Ponder

● To use the Pipe for IPC, the parent process is cloned after creating the pipe
● Now the pipe is available for both the processes
● Sender’s and Receiver’s roles will be fixed, pipe will be configured and used for IPC
● Ony related processes can make use of pipe!

● Two way pipes can be created by opening up two pipes, and properly reassigning the file
descriptors in the child process.
● The pipe() call must be made BEFORE a call to fork(), or the descriptors will not be inherited
by the child!
● With half-duplex pipes, any connected processes must share a related ancestry. Since the
pipe resides within the confines of the kernel, any process that is not in the ancestry for the
creator of the pipe has no way of addressing it

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Named Pipes (FIFO)

● Named pipes can be used to overcome the limitations of Half duplex Unix pipes
● Named pipes exist as a device special file in the file system
● Processes of different ancestry (that are not related each other) can also share data
through a named pipe
● When all I/O is done by sharing processes, the named pipe remains in the file system for
later use
● It provides bidirectional communication
● A named pipe appears as a file and generally processes attach to it for inter-process
communication
● Data is added and removed in a FIFO manner

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Named Pipes (FIFO)

● A named pipe can be created using mkfifo command


● When mkfifo command can be used at the shell prompt
● Try it!
○ [Link]

● We can easily distinguish a pipe from other files using ls -l command*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Named Pipes (FIFO)
● Named pipes can be created in programs using mkfifo() function
○ int mkfifo(const char *pathname, mode_t mode);
○ The first argument specifies the name of the pipe being created - with the directory in
which the pipe is located
○ Second argument indicates the mode in which the pipe is to be operated - for the user,
for the group and for others (like files1)
■ [Link]
○ Function returns -1 on error

● Once the named pipe is created, it should be opened using open() function
○ int open(const char *pathname, int flags)
○ The first argument specifies the name of the pipe being created - with the directory in
which the pipe is located - use the path name that was given with mkfifo function here
○ Second argument indicates the access mode for the named pipe
■ O_RDONLY (Read only)
■ O_WRONLY (Write only)
■ O_RDWR (Read/Write)

● Now the pipe can be read or written using read() or writ()


namedpipe.c
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - named pipes (FIFO)
● Use the pipe for IPC between related process!
1. Parent stores the path name of the named pipe in pipe1
2. Parent creates the named pipe for the path specified in pipe1
3. Parent creates the child
pid = fork()
4. If (pid == 0)
a. Child opens the named pipe in write only mode
b. Child sends a message to the named pipe
else
c. Parent opens the named pipe in read only mode
d. Parent reads and displays the message from the child in the named pipe
e. Parent waits for the child to execute
5. Cose the pipe
6. Stop

See namedpipe2.c
*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - named pipes (FIFO)
● Use the pipe for IPC between related process - in Duplex mode!
1. Parent stores the path name of the named pipe in pipe1
2. Parent creates the named pipe for the path specified in pipe1
3. Parent opens the pipe for writing and leaves a message in the pipe1 (Why this step?!)
4. Parent creates the child
pid = fork()
5. If (pid == 0)
a. Child opens the named pipe in read write mode
b. Child reads the message sent from the parent
c. Child displays the message sent from the parent
d. Child sends a message for the parent
else
e. Parent opens the named pipe in read write mode
f. Parent reads and displays the message from the child in the named pipe
g. Parent sends a message for the child
h. Parent waits for the child to execute
6. Cose the pipe
7. Stop

See [Link] of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - named pipes (FIFO)
● Use the pipe for IPC between unrelated process

● There are two unrelated processes (processes of different ancestry) - Writer and Reader
● Both processes will make use of a named pipe for their communications
● Writer process has to be started first
● As soon as Writer is run, it will create the pipe and leave a message in the pipe
● Reader process will read the pipe after starting
● Both processes can “engage” in conversation until one one them sends “E” to the other

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - named pipes (FIFO)
● Use the pipe for IPC between unrelated process

Writer Process
1. Writer creates the named pipe with read write access
2. Repeat steps 2a to 2i
a. Open the named pipe in Write mode
b. Accept the message to be sent to the reader from the user and store it in arr2
c. Write the arr2 in the named pipe
d. Close the named pipe
e. Open the named pipe in Read mode
f. Read the message from the Reader process from the named pipe into arr1
g. Display the message
h. Close the named pipe
[Check if the Reader would like to terminate]
If (arr1[0] == 'E') goto Step 3
i. [Check if the Writer would like to terminate]
if (arr2[0] == 'E') goto Step 3
3. Stop
Source Code
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - named pipes (FIFO)
● Use the pipe for IPC between unrelated process

Reader Process
1. Reader creates the named pipe myfifo with read write access
2. Repeat steps 2a to 2i
a. Open the named pipe in Read mode
b. Read the message from the Write process from the named pipe into str1
c. Display the message
d. Close the named pipe
e. Accept the message to be sent to the Writer from the user and store it in str2
f. Open the named pipe in Write mode
g. Write the str2 in the named pipe
h. Close the named pipe
[Check if the Writer would like to terminate]
If (str1[0] == 'E') goto Step 3
i. [Check if the Writer would like to terminate]
if (str2[0] == 'E') goto Step 3
3. Stop
Source Code
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Pipes

Facts To Check!

● When we read from a pipe will the data read be removed from the pipe or will it remain there
in the pipe?
● When there are multiple readers reading from a pipe, can all the readers read a particular
data item?
● Can there be multiple writers and multiple readers attempting to write/read from a pipe

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC

● Unix System V (pronounced: "System Five") is one of the first commercial versions of the Unix
operating system
● It was originally developed by AT&T and first released in 1983
● System V Release 4 (SVR4) was commercially the most successful version
● With System V, AT&T introduced three new forms of IPC facilities
○ Message queues
○ Semaphores
○ Shared memory
● Linux has the ability to use System V IPC mechanisms

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC

● Each IPC object (shared memory, message queue or semaphore) has a unique IPC identifier
associated with it
● This identifier is used within the kernel to uniquely identify an IPC object
● To obtain a unique ID, a key must be used
● The key must be mutually agreed upon by both client and server processes
● How to set the value of the key?
○ We can “hardcode” the value - this has the disadvantage of the key possibly being in
use already
○ We can generate the key - ftok() function can be used for this purpose
○ The responsibility of generating a unique key is the burden of the programmer
○ Once the key is made, it can be used for generation of the IPC identifier

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC

The ipcs Command


● Used to obtain the status of all System V IPC objects
● ipcs -q: Show only message queues
● ipcs -s: Show only semaphores
● ipcs -m: Show only shared memory

The ipcrm Command


● Used to remove an IPC object from the kernel
● ipcrm <msg | sem | shm> <IPC ID>

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

● Message queues are linked lists within the kernel’s addressing space
● Messages can be sent to the queue in order and retrieved from the queue in several ways
● As stated earlier each message queue has a unique identifier

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

● Each message has a structure


● It consists of
○ A message type
○ The actual message to be sent
● Message type can be used to identify the type of message being passed (For eg, 1 may
indicate a message from the Server, 2 may indicate a message from the Client, 3 may
indicate an error)
● Message size is restricted to 4096 bytes

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

● Kernel keeps a record of the messages being sent and received


● Kernel creates, stores, and maintains a structure to keep the details of each message queue
● Another data structure is used to keep the permission details of each message queues

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues
Creating / Accessing Message Queues
● A message queue is created or accessed using msgget() function
● int msgget ( key_t key, int msgflg );
● On success the function returns
○ the message queue identifier for a newly created message queue
or
○ the identifier for a queue which exists with the same key value
● On failure the function returns -1
● The first argument is a key value generated using ftok() function
● The second argument can be IPC_CREAT or IPC EXCL
● If IPC_CREAT is used alone, msgget() either returns the message queue identifier for a newly
created message queue, or returns the identifier for a queue which exists with the same key
value
● If IPC_ EXCL is used along with IPC_CREAT, then either a new queue is created, or if the queue
exists, the call fails with -1
● IPC_CREAT can be OR’d with a permission flag such as 0660 - (U)ser / owner can read, can
write and can't execute. (G)roup can read, can write and can't execute. (O)thers can't read,
can't write and can't execute

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues
Sending Messages to the Message Queue
● Once the queue is set, messages can be sent to the message using msgsnd() function
● int msgsnd ( int msqid, struct msgbuf *msgp, int msgsz, int msgflg )
● The first argument is the queue identifier, returned by a previous call to msgsend()
● The second argument is a pointer to the message structure - this structure contains the
message type and the message
● The third argument is the size of the message in bytes, excluding the length of the message
type (4 bytes)
● The fourth argument can be set as IPC_NOWAIT or 0
○ IPC_NOWAIT - If the message queue is full, then the message is not written to the queue,
and control is returned to the calling process. If not specified, then the calling process
will suspend (block) until the message can be written
○ 0 - ignore
● Function returns 0 on success and -1 on failure

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

Receiving Messages from the Message Queue


● Messages can be received from the message using msgrcv() function
● int msgrcv (int msqid, struct msgbuf *msgp, int msgsz, long mtype)
● The first argument is the queue identifier, returned by a previous call to msgsend()
● The second argument is a pointer to the message structure - message from the queue is read
into this structure
● The third argument is the size of the message in bytes, excluding the length of the message
type (4 bytes)
● The fourth argument specifies the type of message to retrieve from the queue
○ 0 - indicates that return the oldest message in the queue
● Function returns
○ Number of bytes copied into message buffer on success and
○ -1 on failure

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

Destroying the Message Queue


● Once the need is over a message queue can be destroyed using the message using msgctl()
function
● int msgctl ( int msgqid, int cmd, struct msqid_ds *buf );
● The first argument is the queue identifier, returned by a previous call to msgsend()
● The second argument is the operation to be performed
○ IPC_RMID - To remove the queue from the kernel
● The third argument is given as NULL if the second argument is IPC_RMID

● Function returns
○ Number of bytes copied into message buffer on success and
○ -1 on failure

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues
Steps to Create a Message Queue

1. Generate unique key using ftok() system call and stores in key
2. Create message queue using the value stored in key and store the IPC Identifier of the
message queue in msgid
3. If (msgid == -1)
Print “Queue can be created”
Goto step 9
4. Prepare the message to be written to the queue
5. Send the message to the queue created in Step 2
6. Read the message in the message queue
7. Display the message
8. Destroy the message queue
9. Stop

Sample Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

● Processes can be related or unrelated


● In either case there has to be a Writer and Reader
● Steps for Writer Process
a. Generate unique key using ftok() system call and stores in key
b. Create message queue using the value stored in key and store the IPC Identifier of the
message queue in msgid
c. Accept the message to be written to the queue from the user
d. Send the message to the queue created in Step b
● Steps for Reader Process
a. Generate unique key using ftok() system call and stores in key
b. Get the identifier of the message queue created by the Writer
c. Read the message sent by the Writer from the message queue
d. Display the message
e. Destroy the message queue

Sample Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Message Queues

Facts To Check!

● When we read from a message queue will the data read be removed from the queue or will
it remain there in the queue?
● When there are multiple readers reading from a queue, can all the readers read a particular
data item?
● Can there be multiple writers and multiple readers attempting to write/read from a message
queue?*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory

● In all IPC mechanisms we learned so far (pipe and message queue), information being shared
is passed through the kernel
● Two reads and two writes are needed
a. Server reads from the input
b. Server writes this data in a message to the pipe, fifo or message queue
c. The client reads the data from the IPC channel
d. The data is written to the client’s buffer

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory

● When IPC is done using shared memory a portion of


primary memory will be reserved as the shared memory
● This memory portion will be used by the participating
processes for writing and reading data
It is the fastest among all IPC mechanisms
● A segment can be created by one process, and
subsequently written to and read from by any number of
processes

● IPC using shared memory can be done as follows:


a. Create and use a shared memory area or use
an existing shared memory area.
b. Attach the processes to the shared memory area
c. Do the read / write operation
d. Detach the processes from the shared memory area and mark it for removal

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory

How to create shared memory segment?


● This memory portion will be used by the participating
processes for writing and reading data
It is the fastest among all IPC mechanisms
● A segment can be created by one process, and
subsequently written to and read from by any number of
processes

● IPC using shared memory can be done as follows:


a. Create and use a shared memory area or use
an existing shared memory area.
b. Attach the processes to the shared memory area
c. Do the read / write operation
d. Detach the processes from the shared memory area and mark it for removal

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory
How to create shared memory segment?
● A shared memory segment is created using shmget() system call
● int shmget ( key_t key, int size, int shmflg)
● The function returns
a. shared memory segment identifier on success
b. -1 on error

● The first argument is the key generated by the ftok() function


● The second argument dictates the size of the shared memory segment
● The third argument can be IPC_CREAT or IPC_EXCL
● If IPC_CREAT is used alone, msgget() either returns the shared memory identifier for a newly
created shared memory segment, or returns the identifier for a shared memory segment
which exists with the same key value
● If IPC_EXCL is used along with IPC_CREAT, then either a new shared memory segment is
created, or if the shared memory segment exists, the call fails with -1
● IPC_CREAT can be OR’d with a permission flag such as 0660 - (U)ser / owner can read, can
write and can't execute. (G)roup can read, can write and can't execute. (O)thers can't read,
can't write and can't execute

Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory
How to attach to a shared memory segment?
● Once a shared memory segment is created, it should be attached using shmat() system call
● int *shmat ( int shmid, char *shmaddr, int shmflg);
● The function returns
a. address at which segment was attached to the process on success
b. -1 on error

● The first argument is the shared segment ID created using shmget()function


a. If the addr argument is zero (0 or NULL), the segment is attached at the first available
address as selected by the system

● The second argument can be


a. SHM_RDONL
■ Attach the segment for read-only access
■ The process must have read permission
■ If this flag is not specified, the segment is attached for read and write access
■ The process must have read and write permission for the segment
■ There is no notion of a write-only shared memory segment
b. SHM_EXEC
■ Execute only access
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory
How to attach to a shared memory segment?
● Once a segment has been properly attached, the process has a pointer to the start of the
segment
● Using the pointer values can be read or written from the segment referencing or deferencing
the pointer

How to remove a shared memory segment?


● Using shmctl () function
● int shmctl ( int shmqid, int cmd, struct shmid_ds *buf )
● The first argument is the shared segment ID created using shmget()function
● To remove the shared memory segment, value of the second argument is given as IPC_RMID
● To remove the shared memory segment, value of the third argument is to be given as 0
● Returns -1 in case of error

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - System V IPC - Shared Memory
In Related Processes
● One process has to create a shared memory segment, and the other process can make use
of that
● Both processes can read or write from the shared memory segment

How to remove a shared memory segment?


● Using shmctl () function
● int shmctl ( int shmqid, int cmd, struct shmid_ds *buf )
● The first argument is the shared segment ID created using shmget()function
● To remove the shared memory segment, value of the second argument is given as IPC_RMID
● To remove the shared memory segment, value of the third argument is to be given as 0
● Returns -1 in case of error

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Shared Memory
● Reading and Writing Data from the Shared Memory in a process
1. Create a shared memory segment and store the ID in shmid
2. Attach the process with the shared memory segment created in Step 1 and store the pointer
to the shared memory segment in shmp
3. Store 5 integers in the shared memory segment
4. Display the data kept in the shared memory segment
5. Detach the shared memory segment
6. Remove the shared memory segment from the memory
7. Stop

See Shared Mem - Simple Read and Write.c


*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Shared Memory
● Reading and Writing Structured Data from the Shared Memory in a process
1. Create a shared memory segment and store the ID in shmid
2. Attach the process with the shared memory segment created in Step 1 and store the pointer
to the shared memory segment in shmp
3. Store the roll number and names of 5 students in the shared memory segment
4. Display the data kept in the shared memory segment
5. Detach the shared memory segment
6. Remove the shared memory segment from the memory
7. Stop

See Shared Mem - Simple Read and Write (Structures).c


*
Why we have to increment shmp when we populate data to the shared memory segment?!

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Shared Memory
● Related Process
1. Create a shared memory segment and store the ID in shmid
2. Attach the process with the shared memory segment created in Step 1 and store the pointer
to the shared memory segment in shmp
3. Store the names and roll numbers of 5 students in the shared memory segment
4. Display the data kept in the shared memory segment
5. Detach the shared memory segment
6. Stop

See Shared Mem - related processes.c


*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Shared Memory
● Related Processes
Note:- In the given program, what will happen if the attachment by the parent to the shared
memory is not done before forking? Will the child process has to do the attachment again?

See Shared Mem - related processes.c


*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Shared Memory
● Use the pipe for IPC between unrelated process

Writer Process
1. Writer creates the shared memory segment and stored the ID in shmid with read write access
2. Write attaches itself to the shared memory segment and stores its pointer in shmp
3. Write data to the shared memory segment
4. Detach the shared memory segment
5. Delete the shared memory segment
Source Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Shared Memory
● Use the pipe for IPC between unrelated process

Reader Process
1. Reader gets the ID of the shared memory segment created by the Writer and store the ID in
shmid with read write access
2. Reader attaches itself to the shared memory segment and stores its pointer in shmp
3. Read the message written by the writer to the shared memory
4. Detach the shared memory segment

5. Stop
Source Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● Socket is also a tool for IPC


● They provide point-to-point, two-way communication between two processes
● Sockets are an endpoint of communication and a name can be bound to them
● A socket can be associated with one or more processes
● There are two widely used socket types, stream sockets, and datagram sockets
● Stream sockets treat communications as a continuous stream of characters, while datagram
sockets have to read entire messages at once
● Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented
protocol, and datagram sockets use UDP (Unix Datagram Protocol), which is unreliable and
message oriented

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● The processes that use a socket can reside on the same system or different systems on
different networks
● Sockets are useful for both stand-alone and network applications
● Sockets allow you to exchange information between processes on the same machine or
across a network, distribute work to the most efficient machine, and they easily allow access
to centralized data
● Socket application program interfaces (APIs) are the network standard for TCP/IP. A wide
range of operating systems support socket APIs

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● TCP provides an ordered and reliable connection between two hosts


● This means that every message sent, TCP guarantees that the message will arrive at the host
in the correct order
● This is achieved at the transport layer so the programmer does not have to worry about this, it
is all done for us

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● A datagram socket uses the User Datagram Protocol (UDP) for sending messages.
● UDP is a much simpler protocol as it does not provide any of the delivery guarantees that TCP
does
● Messages, called datagrams, can be sent to another host without requiring any prior
communication or a connection having been established
● As such, using UDP can lead to lost messages or messages being received out of order
● It is assumed that the application can tolerate an occasional lost message or that the
application will handle the issue of retransmission

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● In network technology, the term port is used in two contexts:


○ The physical meaning of the port
■ For example, network devices such as ADSL Modem, hubs, switches , routers
■ Network equipment interfaces, such as RJ-45 port, and SC port
○ The logical meaning of the port
■ Generally refers to the TCP / IP protocol port
■ Port numbers range from 0 to 65535
■ Ports act as logical communications endpoints for computers and are used on the
Transport layer of the OSI model

Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● A port is a virtual point where network connections start and end


● Ports are software-based and managed by a computer's operating system
● Each port is associated with a specific process or service

● Ports are standardized across all network-connected devices, with each port assigned a
number
● Most ports are reserved for certain protocols — for example,
○ all Hypertext Transfer Protocol (HTTP) messages go to port 80
○ Telnet - Port 23

● While IP addresses enable messages to go to and from specific devices, port numbers allow
targeting of specific services or applications within those devices

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● The lowest numbered 1024 port numbers are used for the most commonly used services.
These ports are called the well-known ports
● Higher-numbered ports are available for general use by applications and are known as
ephemeral ports
● Port is called as a service delivered by a machine and each and every service running with a
particular or customized port (The service is recognized by a port number)

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● Port is a part of the transport layer and helps in network communication


● A port is a logical identifier assigned to a process in order to identify that process uniquely in a
network system
● When two network devices communicate, they do so by sending packets to each other
● Each packet received by a receiver device contains a port number that uniquely identifies the
process where the packet needs to be sent
● Every network protocols do not use a port for communication. For example, ICMP doesn’t use a
port. But protocols like TCP, UDP, HTTP utilize a port for communication

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

Classification of Ports

● Well-known ports
○ Ports in the range 0 to 1023 are assigned and controlled
○ Well-known ports are part of a standardized set of port numbers agreed upon by the Internet
Assigned Numbers Authority (IANA)
● Registered ports
○ Ports in the range 1024 to 49151 are not assigned or controlled, but can be registered to
prevent duplication.
● Dynamic ports
○ Ports in the range 49152 to 65535 are not assigned, controlled, or registered
○ They are used for temporary or private ports
○ They are also known as private or non-reserved ports

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

Classification of Ports

● Well-known ports
○ Ports in the range 0 to 1023 are assigned and controlled
○ Well-known ports are part of a standardized set of port numbers agreed upon by the Internet
Assigned Numbers Authority (IANA)
○ Assigning specific port numbers to well-known services makes it easier for network
administrators and users to identify and recognize the services associated with those ports.
For example, port 80 is conventionally associated with HTTP (Hypertext Transfer Protocol)
○ Well-known ports are reserved for services (such as HTTP, HTTPS, FTP and DNS) that are widely
used on the Internet
○ Many software applications and network devices can be pre-configured to use well-known
ports by default
○ Well-known ports facilitate efficient routing of network traffic by allowing routers and switches
to quickly identify and forward packets associated with specific services based on their port
numbers

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

Classification of Ports

● Registered ports
○ Ports in the range 1024 to 49151 are not assigned or controlled, but can be registered to
prevent duplication.
○ The registration of registered ports is managed by the Internet Assigned Numbers Authority
(IANA)
○ These ports are designated for use by user- or application-level processes and are typically
assigned through a registration process overseen by IANA
○ Example:- HTTP Alt (Alternative) uses port number 8080, MySQL Database Service uses Port
Number 3306

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

Classification of Ports

● Dynamic ports
○ Ports in the range 49152 to 65535 are not assigned, controlled, or registered
○ They are used for temporary or private ports or ephemeral ports or or non-reserved ports
○ These ports are a range of port numbers used by client applications to establish outgoing
network connections
○ These ports are typically assigned by the operating system on the client side from a
designated range, and they are used to facilitate communication between a client and a
server
○ hese ports are assigned temporarily by the client's operating system when an application
initiates an outgoing connection. After the connection is established, the dynamic port is
released and can be reused for other connections

Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket is identified?

● An application can communicate with a remote process by exchanging data with TCP/IP by
knowing the combination of protocol type, IP address, and port number
● This combination is often known as a socket address

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● Socket is also a tool for IPC


● They provide point-to-point, two-way communication between two processes
● Sockets are an endpoint of communication and a name can be bound to them
● A socket can be associated with one or more processes
● There are two widely used socket types, stream sockets, and datagram sockets
● Stream sockets treat communications as a continuous stream of characters, while datagram
sockets have to read entire messages at once
● Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented
protocol, and datagram sockets use UDP (Unix Datagram Protocol), which is unreliable and
message oriented

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● The processes that use a socket can reside on the same system or different systems on
different networks
● Sockets are useful for both stand-alone and network applications
● Sockets allow you to exchange information between processes on the same machine or
across a network, distribute work to the most efficient machine, and they easily allow access
to centralized data
● Socket application program interfaces (APIs) are the network standard for TCP/IP. A wide
range of operating systems support socket APIs

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● TCP provides an ordered and reliable connection between two hosts


● This means that every message sent, TCP guarantees that the message will arrive at the host
in the correct order
● This is achieved at the transport layer so the programmer does not have to worry about this, it
is all done for us

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

● A datagram socket uses the User Datagram Protocol (UDP) for sending messages.
● UDP is a much simpler protocol as it does not provide any of the delivery guarantees that TCP
does
● Messages, called datagrams, can be sent to another host without requiring any prior
communication or a connection having been established
● As such, using UDP can lead to lost messages or messages being received out of order
● It is assumed that the application can tolerate an occasional lost message or that the
application will handle the issue of retransmission

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● In network technology, the term port is used in two contexts:


○ The physical meaning of the port
■ For example, network devices such as ADSL Modem, hubs, switches , routers
■ Network equipment interfaces, such as RJ-45 port, and SC port
○ The logical meaning of the port
■ Generally refers to the TCP / IP protocol port
■ Port numbers range from 0 to 65535
■ Ports act as logical communications endpoints for computers and are used on the
Transport layer of the OSI model

Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● In network technology, the term port is used in two contexts:


○ The physical meaning of the port
■ For example, network devices such as ADSL Modem, hubs, switches , routers
■ Network equipment interfaces, such as RJ-45 port, and SC port
○ The logical meaning of the port
■ Generally refers to the TCP / IP protocol port
■ Port numbers range from 0 to 65535
■ Ports act as logical communications endpoints for computers and are used on the
Transport layer of the OSI model

Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● A port is a virtual point where network connections start and end


● Ports are software-based and managed by a computer's operating system
● Each port is associated with a specific process or service

● Ports are standardized across all network-connected devices, with each port assigned a
number
● Most ports are reserved for certain protocols — for example,
○ all Hypertext Transfer Protocol (HTTP) messages go to port 80
○ Telnet - Port 23

● While IP addresses enable messages to go to and from specific devices, port numbers allow
targeting of specific services or applications within those devices

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● A port is a virtual point where network connections start and end


● Ports are software-based and managed by a computer's operating system
● Each port is associated with a specific process or service

● Ports are standardized across all network-connected devices, with each port assigned a
number
● Most ports are reserved for certain protocols — for example,
○ all Hypertext Transfer Protocol (HTTP) messages go to port 80
○ Telnet - Port 23

● While IP addresses enable messages to go to and from specific devices, port numbers allow
targeting of specific services or applications within those devices

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● The lowest numbered 1024 port numbers are used for the most commonly used services.
These ports are called the well-known ports
● Higher-numbered ports are available for general use by applications and are known as
ephemeral ports
● Port is called as a service delivered by a machine and each and every service running with a
particular or customized port (The service is recognized by a port number)

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● Port is a part of the transport layer and helps in network communication


● A port is a logical identifier assigned to a process in order to identify that process uniquely in a
network system
● When two network devices communicate, they do so by sending packets to each other
● Each packet received by a receiver device contains a port number that uniquely identifies the
process where the packet needs to be sent
● Every network protocols do not use a port for communication. For example, ICMP doesn’t use a
port. But protocols like TCP, UDP, HTTP utilize a port for communication

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

What is a port?

● Well-known ports
○ Ports in the range 0 to 1023 are assigned and controlled

● Registered ports
○ Ports in the range 1024 to 49151 are not assigned or controlled, but can be registered to
prevent duplication.
● Dynamic ports
○ Ports in the range 49152 to 65535 are not assigned, controlled, or registered
○ They are used for temporary or private ports
○ They are also known as private or non-reserved ports
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket is identified?

● An application can communicate with a remote process by exchanging data with TCP/IP by
knowing the combination of protocol type, IP address, and port number
● This combination is often known as a socket address

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket are used in networking?


● Let a client would like to communicate with the server for a particular service
● It creates a socket and chooses any of the free ports available with it

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket are used in networking?


● Let a client would like to communicate with the server for a particular service
● It creates a socket and chooses any of the free ports available with it

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket are used in networking?


● Server will offer the required service through a port which is called as agreed port
● A client can communicate with the agreed port corresponding to the service required

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket are used in networking?


● Server will offer the required service through a port which is called as agreed port
● A client can communicate with the agreed port corresponding to the service required

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket are used in networking?


● A connection between the sockets at the client side and server side is established
● Program at the Client sends the request through the socket at the client side
● The request is channeled to the agreed port at the server side through the port a the the client
side
● Finally the request reaches at the socket at the server side
● Socket will pass the request to the program running at the server side

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a socket are used in networking?
● Let a client communicates with the server
● Server is having a web server and echo server

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket are used in networking?

● Client communicate the server with a request meant for the web server - port number indicate the
service required by the client form the server
● Request is received by the server. Server OS recognizes that the required service is from port no 80
on it
● It forwards the request to port no 80!

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a socket is identified?

● In the UDP protocol, a socket is uniquely identified by the source IP and the source port
● In the TCP protocol, the socket is uniquely identified by the source IP, source port, destination IP,
and destination port

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How socket work?

● Most interprocess communication uses the client server


model
● These terms refer to the two processes which will be
communicating with each other
● One of the two processes, the client, connects to the
other process, the server, typically to make a request for
information

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a sockets work?

1. The socket() API creates a socket for communications and returns a socket
descriptor that represents the socket
2. When an application has a socket descriptor, it can bind a unique name to
the socket. Servers must bind a name to be accessible from the network
3. The listen() API indicates a willingness to accept client connection requests.
When a listen() API is issued for a socket, that socket cannot actively initiate
connection requests. A listen() API must be issued before an accept() API is
issued.
4. The client application uses a connect() API on a stream socket to establish
a connection to the server
5. The server application uses the accept() API to accept a client connection
request. The server must issue the bind() and listen() APIs successfully before
it can issue an accept() API
6. Once a connection is established between sockets (between client and
server), you can use any of the socket API data transfer APIs such as send(),
recv(), read(), write(), and others
7. When a server or client wants to stop operations, it issues a close() API to
release any system resources acquired by the socket

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a sockets work?

1. The socket() API creates a socket for communications and returns a socket
descriptor that represents the socket
2. When an application has a socket descriptor, it can bind a unique name to
the socket. Servers must bind a name to be accessible from the network
3. The listen() API indicates a willingness to accept client connection requests.
When a listen() API is issued for a socket, that socket cannot actively initiate
connection requests. A listen() API must be issued before an accept() API is
issued.
4. The client application uses a connect() API on a stream socket to establish
a connection to the server
5. The server application uses the accept() API to accept a client connection
request. The server must issue the bind() and listen() APIs successfully before
it can issue an accept() API
6. Once a connection is established between sockets (between client and
server), you can use any of the socket API data transfer APIs such as send(),
recv(), read(), write(), and others
7. When a server or client wants to stop operations, it issues a close() API to
release any system resources acquired by the socket
*

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How is a socket created?

● There are two types of sockets


○ Unix Domain Socket
■ Enables efficient communication between processes that are running on the same
device
■ Supports stream-oriented, TCP, and datagram-oriented, UDP, protocols
■ Bounded to a file path

○ Internet Domain Socket


■ Allows processes to communicate over a network
■ Supports stream-oriented, TCP, and datagram-oriented, UDP, protocols
■ Bounded to a IP Address
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a sockets is created? (Common for the client and server)

● To create a socket socket() system call is used


● General form: int sockfd = socket(domain, type, protocol)

● The first argument indicates the domain of the socket


○ AF_UNIX Or AF_LOCAL (Indicates Unix Domain sockets)
○ AF_INET (Indicates IPV4 Internet Domain Sockets)
○ AF_INET6 (Indicates IPV6 Internet Domain Sockets)

● The second argument indicates the type of the socket


○ SOCK_STREAM (Provides sequenced, reliable, two-way, connection-based byte streams - TCP)
○ SOCK_DGRAM (Supports datagrams (connectionless, unreliable messages of a fixed maximum
length - UDP)
● The third argument specifies a particular protocol to be used with the socket
○ Normally only a single protocol exists to support a particular socket type within a given
protocol family, in which case protocol can be specified as 0

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a sockets is created? (Common for the client and server)

● After the creation, the socket is to be bind to the address and port number Or to a path name
● General form: int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

● The first argument indicates the socket ID (returned by a socket() function) of the socket to be bind

● The second argument points to a sockaddr structure containing the address to be bound to the
socket
○ The length and format of the address depend on the address family of the socket (AF_UNIX,
AF_INET, ….)
● The third argument specifies length of the sockaddr structure pointed to by the address argument

● Upon successful completion, bind() shall return 0; otherwise, -1 shall be returned

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a server has to “configure” its socket for accepting connections?

● After binding, server has to keep the socket in the “listen” mode - it waits for the client to approach
the server to make a connection
● General form: int listen(int sockfd, int backlog);

● The first argument indicates the socket ID (returned by a socket() function) of the socket to be bind
● The second argument specifies the limit the number of outstanding connections in the socket's listen
queue
○ A socket may not be readily available for a client at the time it requests for it
○ backlog argument sets the maximum number of clients that can remain in the queue of
pending connections for sockfd
○ Usually the upper limit of this value is specified in SOMAXCONN, defined in <sys/socket.h>

● Upon successful completions, listen() shall return 0; otherwise, -1

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How a server has to accept the client request for a socket connection?

● In the “listen” mode, server may receive a request from a client for a socket connection. Server has
to accept the connection request

● Server uses the accept() call to accept a connection request from a client

● When a connection is available, the socket created is ready for use to read data from the process
that requested the connection

● The call accepts the first connection on its queue of pending connections for the given socket

● The accept() call creates a new socket descriptor with the same properties as the given socket
socket and returns it to the caller

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a server has to accept the client request for a socket connection?

● In the “listen” mode, server may receive a request from a client for a socket connection. Server has
to accept the connection request

● Server uses the accept() call to accept a connection request from a client

● When a connection is available, the socket created is ready for use to read data from the process
that requested the connection

● The call accepts the first connection on its queue of pending connections for the given socket

● The accept() call creates a new socket descriptor with the same properties as the given socket
socket and returns it to the caller

● At this point, the connection is established between client and server, and they are ready to transfer
data
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a server has to accept the client request for a socket connection?

● General form: int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);

● The first argument is the socket ID (for which a listen() call was made by the server)
● The second argument specifies the socket address of the connecting client that is filled in by
accept() before it returns
○ The format of address is determined by the domain that the client resides in
○ This parameter can be NULL if the caller is not interested in the client address. If set to NULL, the
requester's address is not copied into the buffer
● The third argument specifies the address of the location in which the size of the socket structure is to
be filled by the accept() before it returns

● Upon successful completions, accept() returns a nonnegative socket descriptor. Otherwise, it reurns
-1

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a client socket can connect to a socket at the server side?

● Both stream sockets (TCP) and datagram sockets (UDP) can be available for connection
● connect() call is used by the client to connect to a socket
● The connect() is used by the client application to establish a connection between a stream socket
on its side and a server
● For stream sockets, the connect() call attempts to establish a connection between two sockets
● For datagram sockets, the connect() call specifies the peer for a client socket at the server side
● The connect() call performs two tasks when called for a stream socket
○ It completes the binding necessary for a stream socket (in case it has not been previously
bound using the bind() call)
○ It attempts to make a connection to another socket

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How a client socket can connect to a socket at the server side?

● General form: int connect (int socket, const struct sockaddr *address, socklen_t address_len);

● The first argument is the socket ID (created by the client application)


● The second argument is the pointer to a socket address structure containing the address of the
socket to which a connection will be attempted
● The third argument specifies The size of the socket address pointed to by the second argument

● Upon successful completion, connect() returns 0. Otherwise, it returns -1

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to exchange data between the sender and receiver

● send() and recv() functions are used for this purpose


● send() is used to send data to a socket
● recv() is used to receive data from a socket
● General form:
○ num = send(s, addr_of_data, len_of_data, 0);
○ num = recv(s, addr_of_buffer, len_of_buffer, 0);

● The first argument is the socket ID of the socket to be read or written


● The second argument is the address in storage of the buffer that contains, or will contain, the data
(addr_of_data, addr_of_buffer)
● The third argument is the size of this buffer (len_of_data, len_of_buffer)
● The fourth argument is a flag that tells how the data is to be sent - 0 indicates TCP

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to exchange data between the sender and receiver

● send() and recv() functions are used for this purpose in TCP sockets
● send() is used to send data to a socket
● recv() is used to receive data from a socket
● General form:
○ num = send(s, addr_of_data, len_of_data, 0);
○ num = recv(s, addr_of_buffer, len_of_buffer, 0);

● The first argument is the socket ID of the socket to be read or written


● The second argument is the address in storage of the buffer that contains, or will contain, the data
(addr_of_data, addr_of_buffer)
● The third argument is the size of this buffer (len_of_data, len_of_buffer)
● The fourth argument is a flag that tells how the data is to be sent - 0 indicates TCP

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to exchange data between the sender and receiver

● sendto() and recvfrom() functions are used for this purpose in UDP sockets
● send() is used to send data to a socket
● recv() is used to receive data from a socket
● General form:
○ int sendto(int s, char *msg, int len, int flags, struct sockaddr *to, int tolen)
○ int recvfrom(int s, char *msg, int len, int flags, struct sockaddr *from, int *tolen)

● The first argument is the socket ID of the socket from which the data is to be send / received
● The second argument points to the buffer containing the message to be transmitted (msg)
● The third argument is the size of this buffer (len)
● The fourth argument is a flag - a value 0 is passed usually
● The fifth argument is the address of the target socket - in the case of sendto, it is the socket address
where the data is to be sent. In the case of recvfrom, it is the socket address from which data is
received

● The last argument is the size of the structure pointed to by to/from


● If successful, the number of characters sent is returned. The value -1 indicates an error
Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to wind up a socket conversation

● close (s) function is used to tol shuts down the socket associated with the socket descriptor s and
frees resources allocated to the socket

● General form:
○ int close(int s)

● If successful, the function returns 0. -1 indicates an error

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Develop a solution:

● A simple message exchange prototype is sought by our client. (S)he is interested in a method in
which two separate programs can exchange text as message. (S(he also insists a connection
oriented, ordered and reliable mechanism

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-

● Let us see the requirements:-


○ Message exchange is to happen between two applications
○ Since it is not specified that processes are not located in different machines, we assume that
the applications or processes involved in this solution resides in the same machine
○ Only text messages are to be transmitted
○ Whether the message is to exist even after reading it once is also not specified by the client.
Hence we keep it open - message will remain even after it is read first
○ A connection oriented, ordered and reliable mechanism is required
○ It is not clear whether the client and server will engage in a one time exchange or till a
sentinel message is passed by the either party - we assume the first case

● Can you tell me how we can solve this?

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-

● We need to develop a client server pair Let us see the requirements:-


○ Message exchange is to happen between two applications
○ Since it is not specified that processes are not located in different machines, we assume that
the applications or processes involved in this solution resides in the same machine
○ Only text messages are to be transmitted
○ Whether the message is to exist even after reading it once is also not specified by the client.
Hence we keep it open - message will remain even after it is read first
○ Only one message need to be sent and it will be received by the client
○ A connection oriented, ordered and reliable mechanism is required

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-
● The Server process should do the following tasks-
a. Create a TCP socket for data transfer and store the socket ID in server_fd
b. If (server_fd < 0)
Print “Server socket can not be created!”
Goto Step l
c. Call setsockopt() function to set options associated with the socket server_fd
d. Initialize the elements of the server_fd socket structure (IP No. and port no.)
e. Bind the socket server_fd to the port 8080
f. Listen whether there any connection requests from any client
g. Accept a connection request to the socket server_fd and store the newly created socket in
new_socket
h. Read the message stored in the new_socket socket by the client program
i. Write a message for the client in the new_socket socket
j. Close the socket new_socket
k. Close the listening socket server_fd
l. Stop
Code Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-
● The Client process should do the following tasks-
a. Create a TCP socket for data transfer and store the socket ID in socket_ct
b. If (socket_ct < 0)
Print “Client socket can not be created!”
Goto Step i
c. Initialize the elements of the server socket structure (IP No. and port no.)
d. Convert the text IPv4 address to binary and populate to the socket structure of the server
e. Connect the client socket socket_ct to the server socket
f. Write a message for the server in the client_ct socket
g. Read the message stored in the client_ct socket by the server program
h. Close the socket client_ct socket
i. Stop
Code * - Continue frm the next slide on 1st Jan 2024

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Develop a solution:

● A simple message exchange prototype is sought by our client. (S)he is interested in a method in
which two separate programs can exchange text as message. (S(he is interested to see a
prototype which is free from any connection oriented reliable mecahisms

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-

● We need to develop a client server pair. Let us see the requirements:-


○ Message exchange is to happen between two applications
○ Since it is not specified that processes are not located in different machines, we assume that
the applications or processes involved in this solution resides in the same machine
○ Only text messages are to be transmitted
○ Whether the message is to exist even after reading it once is also not specified by the client.
Hence we keep it open - message will remain even after it is read first
○ Only one message need to be sent and it will be received by the client
○ Just a mechanism for message exchange is required - no connection, acknowledgement,
reliable stuff required!

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use UDP sockets for IPC?

Solution:-
● The Server process should do the following tasks-
a. Create a UDP socket for data transfer and store the socket ID in server_fd
b. If (server_fd < 0)
Print “Server socket can not be created!”
Goto Step h
c. Initialize the elements of the server_fd socket structure (IP No. and port no.)
d. Bind the socket server_fd to the port 5000
e. Read the message stored from the client socket
f. Gather the client socket details (IP Address, port number) and populate in the structure for the
client socket details
g. Display the data from sent by the client
h. Send a message for the client socket
i. Stop
Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use UDP sockets for IPC?

Solution (without using connect() function by the client):-


● The Client process should do the following tasks-
a. Create a UDP socket for data transfer and store the socket ID in socket_ct
b. If (socket_ct < 0)
Print “Client socket can not be created!”
Goto Step h
c. Initialize the elements of the server socket structure (IP No. and port no.)
d. Write a message for the server
e. Read the message from the server and display it
f. Close the socket
g. Stop
Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use UDP sockets for IPC?
UDP (Client Socket without using connect() system call)
Note:-

● In the above solution, client does not make a connect() system call
● When the recvfrom function is executed first, it waits for a UDP packet to arrive. When a packet is
received, the function extracts the data from the packet and fills in the buffer with the received data.
Additionally, it updates the client socket address structure with information about the client's address
(IP address and port)
● In the sendto function, we explicitly provide the server's address information. The operating system
uses this information to send the UDP packet to the specified server. The server can then use this
information when calling recvfrom to determine the source of the received UDP packet.

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use UDP sockets for IPC?
UDP (Client Socket without using connect() system call)
Note:-

● For sending and receiving data to/from the server socket, client uses sendto and recvfrom functions
● When sendto and recvfrom functions, each time we have to specify the details for the target socket
● This is is the agility provided by the UDP sockets - In UDP, each datagram (packet) is independent of
the others, and there is no ongoing connection like in TCP. As a result, a UDP client socket can send
and receive data from multiple UDP server sockets!
● The client can send datagrams to different servers by specifying the destination address and port for
each sendto operation. Similarly, when the client uses recvfrom to receive data, it can get
datagrams from any server that sent data to the specified client's address and port!

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use UDP sockets for IPC?

Solution (using connect statement by the client):-


● The Client process should do the following tasks-
a. Create a UDP socket for data transfer and store the socket ID in socket_ct
b. If (socket_ct < 0)
Print “Client socket can not be created!”
Goto Step h
c. Initialize the elements of the server socket structure (IP No. and port no.)
d. Connect the client socket socket_ct to the server
e. Write a message for the server
f. Read the message from the server and display it
g. Close the socket
h. Stop
Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use UDP sockets for IPC?
UDP (Client Socket with using connect() system call)

Note:-

● In the above solution, client make a connect() system call to the server socket prior to sending and
receiving data
● In such cases, instead of sendto and recvfrom functions, client can use send and recv functions, as
the default target socket is set by the connect statement
● When the target socket is fixed throughout in a UDP transaction, the client can use the connect() call
to set the target socket
● But when the client need to send to or receive data from a different server socket, still it has to use
the sendto and recvfrom functions!

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Develop a solution:

● A simple message exchange prototype is sought by our client. (S)he is interested in a method in
which two separate programs can exchange text as message. Message exchange should be
continued till either party send a termination signal

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-

● We need to develop a client server pair. Let us see the requirements:-


○ Message exchange is to happen between two applications
○ Since it is not specified that processes are not located in different machines, we assume that
the applications or processes involved in this solution resides in the same machine
○ Only text messages are to be transmitted
○ Whether the message is to exist even after reading it once is also not specified by the client.
Hence we keep it open - message will remain even after it is read first
○ Message exchange has to terminate when either party issue a “Stop” as the message
○ Just a mechanism for message exchange is required - no connection, acknowledgement,
reliable stuff is specified! *

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use a connection oriented
socket (Stream Socket or TCP Socket)?

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-
● The Server process should do the following tasks-
a. Create a TCP socket for data transfer and store the socket ID in server_fd
b. If (server_fd < 0)
Print “Server socket can not be created!”
Goto Step l
c. Call setsockopt() function to set options associated with the socket server_fd
d. Initialize the elements of the server_fd socket structure (IP No. and port no.)
e. Bind the socket server_fd to the port 8080
f. Listen whether there any connection requests from any client
g. Accept a connection request to the socket server_fd and store the newly created socket in
new_socket
[Begin chat with the client using chatt subroutine]
h. Call chatt (new_socket)
i. Close the socket new_socket
j. Close the listening socket server_fd
k. Stop
Code Department of Information Technology, Kannur University
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use sockets for IPC?

Solution:-
Chatt subroutine (connfd)
Repeat steps 1 to 5 until buff contains “stop”
1. Fill the message buffer buff with NULL values
2. Read the message from the client using socket fd connfd and store it in buff and display it
3. Read a line of text from the user and store it in buff
4. Send the contents of buff to the client through the socket ID connfd
5. If buff == “Stop” Goto step 6
6. Return
Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to use TCP sockets for IPC?

Solution:-
● The Client process should do the following tasks-
a. Create a TCP socket for data transfer and store the socket ID in socket_ct
b. If (socket_ct < 0)
Print “Client socket can not be created!”
Goto Step i
c. Initialize the elements of the server socket structure (IP No. and port no.)
d. Connect the client socket socket_ct to the server socket
e. Call chatt(socket_ct)
f. Close the socket client_ct socket
g. Stop
Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How to use sockets for IPC?

Solution:-
Chatt subroutine (connfd)
Repeat steps 1 to 5 until buff contains “stop”
1. Fill the message buffer buff with NULL values
2. Read a line of text from the user and store it in buff
3. Send the contents of buff to the server through the socket ID connfd
4. Fill the message buffer buff with NULL values
5. Read the message from the server using socket fd connfd and store it in buff and display it
6. If buff == “Stop” Goto step 7
7. Return
Code

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Structure of Sockets - TCP Socket

● The socket data structure defines the socket


● During a socket subroutine, the system dynamically creates the socket data structure

sockaddr
● This is a generic socket address structure, which will be passed in most of the socket function
calls

struct sockaddr {
unsigned short sa_family;
char sa_data[14];
};

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Structure of Sockets - TCP Socket

● The socket data structure defines the socket


● During a socket subroutine, the system dynamically creates the socket data structure

● The type of socket addresses will vary depending upon the protocol and its type

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Structure of Sockets - TCP Socket

● The socket data structure defines the socket


● During a socket subroutine, the system dynamically creates the socket
data structure

sockaddr_in

struct sockaddr_in {
short int sin_family;
unsigned short int sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[8];
};

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Structure of Sockets - TCP Socket

● The socket data structure defines the socket


● During a socket subroutine, the system dynamically creates the socket
data structure

sockaddr_un
(Unix Domain Sockets)

struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* Pathname */
};

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Structure of Sockets - TCP Socket

● The socket data structure defines the socket


● During a socket subroutine, the system dynamically creates the socket
data structure

sockaddr_un
(Unix Domain Sockets)

struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* Pathname */
};

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets

How to use UDP socket to create a chat application?

How to engage in IPC between processes in different devices?

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
“Helper” Functions that we use in socket programming

● There are many functions such as bzero(), read() and write() that we have used in our sample
programs
● A gist of few of these functions are available at
[Link]
0function%20places%20nbyte,function%20does%20not%20return%20anything.

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
How to know about port numbers?

● To create a socket a port number is necessary


● Port numbers vary from 0 - 65534
● A client need to know the IP address of the server and the port number that offer the service from
the server - how is it possible?

● To resolve the problem of identifying a particular server process running on a host, both TCP and
UDP have defined a group of well-known ports.
● Port numbers smaller than 1024 are considered well-known
○ For example, telnet uses port 23, http uses 80, ftp uses 21
○ These port numbers can be readily used by a client to get those services from a server -
server should be configured to offer the services

● For our purpose, a port will be defined as an integer number between 1024 and 65535
● The port assignments to network services can be found in the file /etc/services
● When we create our own server, we have to take that port numbers we use will not clash with with
any other server

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Byte Orders in Sockets

● Machines store Multi Byte value in different orders, spending on its architecture
● Consider a 16-bit internet that is made up of 2 bytes
● There are two ways to store this value

○ Little Endian − In this scheme, low-order byte is stored on the starting address (A) and
high-order byte is stored on the next address (A + 1)

○ Big Endian − In this scheme, high-order byte is stored on the starting address (A) and
low-order byte is stored on the next address (A + 1)

● When machines with different byte order conventions communicate with each other, there has to
be a common agreement on the byte order of the bytes being transferred
● The Internet protocols specify a canonical byte order convention for data transmitted over the
network. This is known as Network Byte Order

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Byte Orders in Sockets

● Host byte order and network byte order refer to the way data is represented in computer memory
and how it is transmitted over a network

● Host Byte Order

○ The order in which a computer's CPU stores multi-byte data types, such as integers and
floating-point numbers, in its memory
○ The byte order is dependent on the architecture of the CPU - big-endian and little-endian
○ In a big-endian system, the most significant byte (MSB) is stored at the lowest memory
address, while in a little-endian system, the least significant byte (LSB) is stored at the lowest
memory address

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Byte Orders in Sockets

● Host byte order and network byte order refer to the way data is represented in computer memory
and how it is transmitted over a network

● Network Byte Order

○ A standardized order used for transmitting data over a network


○ It is defined to be big-endian, meaning the most significant byte comes first in the data
stream
○ This standardization ensures that when data is sent from one computer to another over a
network, there is consistency in how multi-byte values are represented

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Byte Orders in Sockets - Network Byte Order

● Network byte order, defines the bit-order of network addresses as they pass through the network
● The TCP/IP standard network byte order is big-endian
● In order to participate in a TCP/IP network, little-endian systems have to convert their addresses
into network byte order

● You might have noticed that in the code samples we have used, while establishing the Internet
socket connection, the data in the sin_port and sin_addr members of the sockaddr_in structure
are represented in Network Byte Order using one of the following functions:

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Sockets
Byte Orders in Sockets - Network Byte Order

● htons() (Host to Network Short): This function takes a 16-bit (2-byte) short integer in host byte order
and converts it to network byte order (big-endian)
● htonl() (Host to Network Long): This function takes a 32-bit (4-byte) long integer in host byte order
and converts it to network byte order (big-endian)
● ntohs() (Network to Host Short): This function takes a 16-bit (2-byte) short integer in network byte
order and converts it to host byte order (based on the host's endianness)
● ntohl() (Network to Host Long): This function takes a 32-bit (4-byte) long integer in network byte
order and converts it to host byte order (based on the host's endianness)

Department of Information Technology, Kannur University


MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Data Preservation after the first read)
IPC Mechanism Data Preservation

Half duplex pipe Data is removed from the pipe once it is read by the reader

Named pipe Depends on the data transfer mode. In message mode, data is
not preserved. In byte mode, data is partially preserved*

Message queue Data is removed from the queue once it is read by the reader.
Additional setting can be made to preserve the data, if required

Shared memory Data is preserved in the shared memory until it is explicitly modified
or deleted
*In message mode, each write operation by a process is considered a message, and each read operation by another process
reads an entire message. In byte mode, data is written and read as a stream of bytes, without any message boundaries. .In
message mode, the data read by a reader is not preserved in the pipe once it is read. The reader consumes the entire message
and removes it from the pipe. However, in byte mode, the data read by a reader is partially preserved in the pipe, depending on
how many bytes the reader requests. The reader only consumes the number of bytes it requests, and the remaining bytes are left in
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Data Preservation after the first read)
IPC Mechanism Data Preservation

TCP Socket Data is not preserved; but it is reliably delivered to the target

UDP Socket Data is not preserved; but it is not guaranteed to be delivered to


the target

Unix Domain Socket Depends on the socket type. For stream sockets, yes. For
datagram sockets, no
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Preservation of IPC Mechanism after
the termination of execution of its creator)

IPC Mechanism Retained in Memory After Creator Process Terminates

Half Duplex Pipe Pipe is closed and resources are released, when the last process closes it

Named Pipe (FIFO) The named pipe persists in the secondary memory as long as it is explicitly removed or the system is rebooted

Depends on the system and implementation; some systems retain the queue after the creator process
Message Queue
terminates, while others may automatically clean up resources

Shared Memory Shared memory segments persist until explicitly removed or until the system is rebooted

TCP and UDP Sockets The socket is closed when the process terminates
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Order in which data is added or
written)

IPC Order of Data Writing Data


Mechanism

Half duplex FIFO - the data is written and read in the same order as it was sent
pipe

Named pipe FIFO - the data is written and read in the same order as it was sent

Message FIFO or priority-based - the data is written and read in the same order as it was sent, or based on the
queue priority assigned to each message
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Order in which data is added or
written) - Continued

IPC Order of Data Writing Data


Mechanism

Shared Arbitrary - the data is written and read in any order, depending on the synchronization mechanism
memory used by the processes

TCP Socket FIFO - the data is written and read in the same order as it was sent, and the transmission is reliable
and error-free

UDP Socket Arbitrary - the data is written and read in any order, and the transmission is unreliable and may lose
or reorder packets

Unix Domain FIFO or arbitrary - the data is written and read in the same order as it was sent, or in any order,
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Order in which data is read)
IPC Order of Data Reading
Mechanism

Half duplex FIFO - the data is read in the same order as it was written
pipe

Named pipe FIFO - the data is read in the same order as it was written

Message FIFO or priority-based - the data is read in the same order as it was sent, or based on the
queue priority assigned to each message

Shared Arbitrary - the data is read in any order, depending on the synchronization mechanism used
memory by the processes
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Order in which data is read) -
Continued

IPC Order of Data Reading


Mechanism

TCP Socket FIFO - the data is read in the same order as it was written, and the transmission is reliable and
error-free

UDP Socket Arbitrary - the data is read in any order, and the transmission is unreliable and may lose or
reorder packets

Unix Domain FIFO or arbitrary - the data is read in the same order as it was written, or in any order,
Socket depending on the type of socket (stream or datagram) and the transmission reliability
MCCSA01DSC03 COMPUTER NETWORK AND LINUX ADMINISTRATION
Inter Process Communication (IPC) - Comparison of IPC Mechanisms (Use of Structured Data)

IPC Mechanism Use of Structured Data

Half duplex pipe No, the data is written as a stream of bytes

Named pipe No, the data is written as a stream of bytes

Message queue Yes, the data is written as a message with a fixed size and format

Shared memory Yes, the data can be written as a memory object with a defined structure

TCP Socket, UDP Allows the transmission of structured data. The interpretation of the data structure is up to
Socket, Domain the application logic on both the sender and receiver sides
Socket

You might also like