Вы находитесь на странице: 1из 62

Linux Programming

Unit-V IPC

COURSE OUTCOMES
1. Understand various Linux System utilities.
2. Demonstrate the shell scripts in shell Environment.
3. Understand the basic principles of file system architecture.
4. Apply the core concept of Process management and implement in the Linux Environment.
5. Compare various Inter-Process communication and Client-Server Application techniques In Linux environment
IPC
 Inter-Process-Communication (or IPC for short)
are mechanisms provided by the kernel to allow
processes to communicate with each other.
 Pipes
 Named Pipes or FIFOs
 Message Queues
 Shared memory
 Semaphores
 Sockets
Pipe
 A pipe is a connection between two processes, such that the
standard output from one process becomes the standard input of
the other process.
 In UNIX Operating System, Pipes are useful for communication
between related processes(inter-process communication)
Pipe
 Pipe is one-way communication only i.e we can use a pipe such
that One process write to the pipe, and the other process reads
from the pipe.
 The pipe can be used by the creating process, as well as all its
child processes, for reading and writing.
 If a process tries to read before something is written to the pipe,
the process is suspended until something is written.
 The pipe system call finds the first two available positions in the
process’s open file table and allocates them for the read and write
ends of the pipe.
Process Pipes
 Parent and child sharing a pipe
 When fork is used in any process, file descriptors remain open
across child process and also parent process.
 If the fork is called after creating a pipe, then the parent and child
can communicate via the pipe.
Pipes system call
 SYSTEM CALL: pipe();
int pipe( int fd[2] );
 RETURNS: 0 on success
-1 on error: errno = EMFILE (no free descriptors)
EMFILE (system file table is full)
EFAULT (fd array is not valid)
fd[0] is set up for reading, fd[1] is set up for writing

The first integer in the array (element 0) is set up and opened for
reading, while the second integer (element 1) is set up and opened
for writing.
popen( )
 Creating a pipe using popen()
 LIBRARY FUNCTION: popen();
PROTOTYPE: FILE *popen ( char *command, char *type);
RETURNS: new file stream on success
NULL on unsuccessful fork() or pipe() call
creates a pipe, and performs fork/exec operations using "command"
 This standard library function creates a half-duplex pipeline by
calling pipe() internally.
 It then forks a child process, execs the Bourne shell, and executes
the "command" argument within the shell.
 Direction of data flow is determined by the second argument,
"type". It can be "r" or "w", for "read" or "write".
Pclose( )
 LIBRARY FUNCTION: pclose();
 PROTOTYPE: int pclose( FILE *stream );
 RETURNS: exit status of wait() call
-1 if "stream" is not valid, or if wait4() fails

 waits on the pipe process to terminate, then closes the stream.


 Pipes which are created with popen() must be closed with
pclose()
 The pclose() function performs a wait4() on the process forked
by popen(). When it returns, it destroys the pipe and the file
stream.
Pipe program
 #include <stdio.h>
 #include <unistd.h>
 #include <sys/types.h>
 int main(void)
 { int fd[2], nbytes;
 pid_t childpid;
 char string[] = "Hello, world!\n“, readbuffer[80];
 pipe(fd);
 if((childpid = fork()) == -1)
 { perror("fork"); exit(1); }
 if(childpid == 0)
 { close(fd[0]); /* Child process closes up input side of pipe */
 /* Send "string" through the output side of pipe */
 write(fd[1], string, (strlen(string)+1));
 exit(0); }

Pipe program
 else
 {
 /* Parent process closes up output side of pipe */
 close(fd[1]);

 /* Read in a string from the pipe */
 nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
 printf("Received string: %s", readbuffer);
 }

 return(0);
 }
Pipe program steps
 The steps involved for communication via unnamed pipes:

 1. Create the pipe(s) needed.


 2. Generate the child process(es).
 3. Close/duplicate file descriptors to properly associate the ends
of the pipe.
 4. Close the unneeded ends of the pipe.
 5. Perform the communication activities.
 6. Close any remaining open file descriptors.
 7. If appropriate, wait for child processes to terminate.
Named Pipe (FIFO)
 Named pipes or (FIFO)
 A named pipe works much like a regular pipe, but does have
some noticeable differences.
 Named pipes exist as a device special file in the file system.
 Processes of different ancestry can 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.
 FIFO’s allows bidirectional communication between processes
Named Pipe (FIFO)
 Creating a FIFO
 There are several ways of creating a named pipe. The first two can be done
directly from the shell.
 mknod MYFIFO p
 mkfifo a= rw MYFIFO
 The above two commands perform identical operations, with one exception.
 The mkfifo command provides a hook for altering the permissions on the
FIFO file directly after creation.
 With mknod, a quick call to the chmod command will be necessary.
 FIFO files can be quickly identified in a physical file system by the ``p'' indicator
seen here in a long directory listing:
 $ ls -l MYFIFO
 prw-r--r-- 1 root root 0 Dec 14 22:15 MYFIFO|
Named Pipe (FIFO) : mknod()
 the mknod() system call
 mknod();
 PROTOTYPE: int mknod( char *pathname, mode_t mode, dev_t dev);
RETURNS: 0 on success,
 -1 on error: errno = EFAULT (pathname invalid)
 EACCES (permission denied)
 ENAMETOOLONG (pathname too long)
 ENOENT (invalid pathname)
 ENOTDIR (invalid pathname)
 Creates a filesystem node (file, device file, or FIFO)
FIFO Operations
 I/O operations on a FIFO are essentially the same as for normal
pipes, with once major exception.
 An ``open'' system call or library function should be used to
physically open up a channel to the pipe.
 With half-duplex pipes, this is unnecessary, since the pipe resides
in the kernel and not on a physical file system.
 In our examples, we will treat the pipe as a stream, opening it up
with fopen(), and closing it with fclose().
FIFO Program
 Server program  Client program
 #include <stdio.h>  #include <stdio.h>
 #include <stdlib.h>  #include <stdlib.h>
 #include <sys/stat.h>
 #define FIFO_FILE "MYFIFO"
 #include <unistd.h>
 #include <linux/stat.h>  int main(int argc, char *argv[])
 #define FIFO_FILE "MYFIFO"  { FILE *fp;
 int main(void)  if ( argc != 2 ) {
 { FILE *fp;
printf("USAGE: fifoclient [string]\n");
 char readbuf[80];
 umask(0);  exit(1); }
mknod(FIFO_FILE, S_IFIFO|0666, 0); if((fp = fopen(FIFO_FILE, "w")) == NULL)
while(1) { perror("fopen");
{ fp = fopen(FIFO_FILE, "r");  exit(1); }
 fgets(readbuf, 80, fp);
 fputs(argv[1], fp);
printf("Received string: %s\n", readbuf);
 fclose(fp); }  fclose(fp);
 return(0); }  return(0); }
PIPE Vs FIFO
 Unnamed pipe:  Named Pipe:( also called FIFO)
1) They are created programmatically
1) These are created by the using the command mkfifo.
shell automatically. 2) They exists in the file system with a
 given file name.
3) They can be viewed and accessed by
2) They exists in the kernel.
any two un-related processes. ls cmd
 shows "p" in the permission bits for a
3) They can not be accesses named pipe.
by any process, including the 4) They are not opened while creation.
5) They are Bi-directinoal.
process that creates it. 6) A process writing a named pipe
 blocks until there is a process that reads
4) They are opened at the that data.
time of creation only. 7) Broken pipe error occurs when the
writing process closes the named pipe
 while another reading process reads it.
5) They are unidirectional.
semaphores:
 Semaphores let processes query or alter status information.
 They are often used to monitor and control the availability of
system resources such as shared memory segments.

 Basically semaphores are classified into two types −


 Binary Semaphores − Only two states 0 & 1, i.e.,
locked/unlocked or available/unavailable, Mutex implementation.
 Counting Semaphores − Semaphores which allow arbitrary
resource count are called counting semaphores.
semaphores:
 To perform synchronization using semaphores, following are the
steps −
 Step 1 − Create a semaphore or connect to an already existing
semaphore (semget())
 Step 2 − Perform operations on the semaphore i.e., allocate or
release or wait for the resources (semop())
 Step 3 − Perform control operations on the message queue
(semctl())
semaphores:semget()
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/sem.h>
int semget(key_t key, int nsems, int semflg)
 Arguments need to be passed −
 The first argument key : recognizes the message queue.
 The second argument, nsems : specifies the number of
semaphores. If binary then it is 1, otherwise as per the required
count of number of semaphore sets.
 The third argument, semflg : specifies the required semaphore
flag/s such as IPC_CREAT or IPC_EXCL (used with IPC_CREAT
to create semaphore and the call fails, if a semaphore already
exists).
 return valid semaphore identifier on success
 -1 in case of failure.
semaphores:semop()
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/sem.h>
int semop(int semid, struct sembuf *semops, size_t nsemops)
Arguments need to be passed −
 The first argument, semid : indicates semaphore set identifier
created by semget().
 The second argument, semops : is the pointer to an array of
operations to be performed on the semaphore set.
 The structure is as follows
struct sembuf
{ unsigned short sem_num; /* Semaphore set num */
short sem_op; /* Semaphore operation */
short sem_flg; /* Operation flags, IPC_NOWAIT, SEM_UNDO */
};
semaphores:semop()
 sem_op, in the above structure, indicates the operation that
needs to be performed −
 If sem_op is –ve, allocate or obtain resources. Blocks the calling
process until enough resources have been freed by other processes,
so that this process can allocate.
 If sem_op is zero, the calling process waits or sleeps until semaphore
value reaches 0.
 If sem_op is +ve, release resources.

 struct sembuf sem_lock = { 0, -1, SEM_UNDO };


 struct sembuf sem_unlock = {0, 1, SEM_UNDO };
The third argument, nsemops: is the number of operations in that
array.
semaphores:semctl()
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/sem.h>
int semctl(int semid, int semnum, int cmd, …)
 This system call performs control operation for a semaphore.
 The following arguments need to be passed −
 The first argument, semid : is the identifier of the semaphore.
This id is the semaphore identifier, which is the return value of semget()
system call.
 The second argument : semnum, is the number of semaphore. The
semaphores are numbered from 0.
 The third argument, cmd: is the command to perform the required
control operation on the semaphore.
 The fourth argument, of type, union semun, depends on the cmd. For
few cases, the fourth argument is not applicable.
semaphores:data structure
 The semid_ds data structure which is defined in sys/sem.h is as
follows −
 struct semid_ds {
 struct ipc_perm sem_perm; /* Permissions */
 time_t sem_otime; /* Last semop time */
 time_t sem_ctime; /* Last change time */
 unsigned long sem_nsems; /* Number of semaphores in the set */
 };
message queues:
 A message queue is a linked list of messages stored within the kernel
and identified by a message queue identifier.
 Communication using message queues can happen in the following
ways −
 Writing into the shared memory by one process and reading from
the shared memory by another process.
 As we are aware, reading can be done with multiple processes as
well.

message queues:
 Writing into the shared memory by one process with different data
packets and reading from it by multiple processes, i.e., as per message
type.

 To perform communication using message queues, following are the


steps −
 Step 1 − Create a message queue or connect to an already existing
message queue (msgget())
 Step 2 − Write into message queue (msgsnd())
 Step 3 − Read from the message queue (msgrcv())
 Step 4 − Perform control operations on the message queue
(msgctl())
message queues:msgget()
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/msg.h>
 int msgget(key_t key, int msgflg)
 This system call creates or allocates a message queue.
 Following arguments need to be passed −
 The first argument, key, recognizes the message queue. The key can
be either an arbitrary value or one that can be derived from the
library function ftok().
 The second argument, shmflg, specifies the required message queue
flag/s such as IPC_CREAT (creating message queue if not exists) or
IPC_EXCL
 This call would return a valid message queue identifier on success
and -1 in case of failure. EACCESS , EEXIST , ENOENT, ENOMEM
message queues:msgsnd()
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/msg.h>
 int msgsnd(int msgid, const void *msgp, size_t msgsz, int msgflg)
 This system call creates or allocates a message queue.
 Following arguments need to be passed −
 The first argument, msgid : recognizes the message queue i.e., message
queue identifier. The identifier value is received upon the success of
msgget()
 The second argument, msgp : is the pointer to the message, sent to the
caller, defined in the structure of the following form −
 struct msgbuf {
 long mtype;
 char mtext[1];
 };
message queues:msgsnd()
 The variable mtype is used for communicating with different message
types, explained in detail in msgrcv() call.
 The variable mtext is an array or other structure whose size is
specified by msgsz (positive value).
 If the mtext field is not mentioned, then it is considered as zero size
message, which is permitted.
 The third argument, msgsz : It is the size of message
 The fourth argument, msgflg : indicates certain flags such as
IPC_NOWAIT or MSG_NOERROR
 This call would return 0 on success and -1 in case of failure.
message queues:msgrcv()
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgrcv(int msgid, const void *msgp, size_t msgsz, long msgtype, int
msgflg)
 This system call retrieves the message from the message queue.
Following arguments need to be passed −
 The first argument, msgid, recognizes the message queue i.e., the
message queue identifier. The identifier value is received upon the
success of msgget()
 The second argument, msgp, is the pointer of the message received
from the caller
message queues:msgrcv()
 The third argument, msgsz, is the size of the message received
 The fouth argument, msgtype, indicates the type of message −
◦ If msgtype is 0 − Reads the first received message in the queue
◦ If msgtype is +ve − Reads the first message in the queue of type
msgtype
◦ If msgtype is –ve − Reads the first message of lowest type less
than or equal to the absolute value of message type
 The fifth argument, msgflg, indicates certain flags such as
IPC_NOWAIT or MSG_NOERROR
This call would return the number of bytes actually received in mtext
array on success and -1 in case of failure.
message queues:msgctl()
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/msg.h>
 int msgctl(int msgid, int cmd, struct msqid_ds *buf)
This system call performs control operations of the message queue
(System V). Following arguments need to be passed −
 The first argument, msgid, recognizes the message queue i.e., the
message queue identifier. The identifier value is received upon the
success of msgget()
 The second argument, cmd, is the command to perform the required
control operation on the message queue.Valid values for cmd are −
 IPC_STAT − Copies information of the current values of each
member of struct msqid_ds to the passed structure pointed by buf.
message queues:msgctl()
 This command requires read permission on the message queue.
 IPC_SET − Sets the user ID, group ID of the owner, permissions etc
pointed to by structure buf.
 IPC_RMID − Removes the message queue immediately.
 IPC_INFO − Returns information about the message queue limits
and parameters in the structure pointed by buf,
 MSG_INFO − Returns an msginfo structure containing information
about the consumed system resources by the message queue.
 The third argument, buf, is a pointer to the message queue structure
named struct msqid_ds.
 This call would return the value depending on the passed command.
Success of IPC_INFO and MSG_INFO or MSG_STAT returns the
index or identifier of the message queue or 0 for other operations and
-1 in case of failure.
message queues: limits

There are three system wide limits regarding the message queues.
These are,
 MSGMNI, maximum number of queues in the system.
 MSGMAX, maximum size of a message in bytes.
 MSGMNB, which is the maximum size of a message queue.
 We can see these limits with the ipcs -l command.
 $ ipcs –l
 ------ Messages Limits --------
 max queues system wide = 32000
 max size of message (bytes) = 8192
 default max size of queue (bytes) = 16384
message queues:program
 #include <stdio.h>  #include <stdio.h>
 #include <sys/ipc.h>  #include <sys/ipc.h>
 #include <sys/msg.h>  #include <sys/msg.h>
 struct mesg_buffer {  struct mesg_buffer {
 long mesg_type;  long mesg_type;
 char mesg_text[100];  char mesg_text[100];
 } message;  } message;
 int main()  int main()
 { key_t key;  {
 int msgid;  key_t key;
 key = ftok("progfile", 65);  int msgid;
msgid = msgget(key, 0666 | IPC_CREAT);  key = ftok("progfile", 65);
 message.mesg_type = 1; msgid = msgget(key, 0666 | IPC_CREAT);
 printf("Write Data : "); msgrcv(msgid, &message, sizeof(message),
 gets(message.mesg_text); 1, 0);
msgsnd(msgid, &message, sizeof(message), 0);  printf("Data Received is : %s \n",
printf("Data send is : %s \n", message.mesg_text);  message.mesg_text);
 return 0; }  msgctl(msgid, IPC_RMID, NULL);
 return 0; }
shared memory :
 Inter Process Communication through shared memory is a concept
where two or more process can access the common memory.
 And communication is done via this shared memory where changes
made by one process can be viewed by another process.
 Shared memory is well suited to larger collections of data and,
because it uses memory, grants fast, random access.
shared memory :
 the shared memory what needs to be done with the system calls−

 Create the shared memory segment or use an already created shared


memory segment (shmget())
 Attach the process to the already created shared memory segment
(shmat())
 Detach the process from the already attached shared memory
segment (shmdt())
 Control operations on the shared memory segment (shmctl())
shared memory : shmget()
 #include <sys/ipc.h>
 #include <sys/shm.h>
 int shmget(key_t key, size_t size, int shmflg)
 The above system call creates or allocates a shared memory segment.
The arguments that need to be passed are as follows −
 The first argument, key : recognizes the shared memory segment.
The key can be either an arbitrary value or one that can be derived
from the library function ftok().
 The second argument, size, is the size of the shared memory.
 The third argument, shmflg, specifies the required shared memory
flag/s such as IPC_CREAT (creating new segment) or IPC_EXCL

This call would return a valid shared memory identifier on success and
-1 in case of failure
shared memory : shmat()
 #include <sys/types.h>
 #include <sys/shm.h>
 void * shmat(int shmid, const void *shmaddr, int shmflg)
 The above system call performs attaching a shared memory segment
to the address space of the calling process.
 The arguments that need to be passed are as follows −
 The first argument, shmid, is the identifier of the shared memory
segment.
 The second argument, shmaddr, is to specify the attaching
address. If shmaddr is NULL, the system by default chooses the
suitable address to attach the segment.
 If shmaddr is not NULL and SHM_RND is specified in shmflg, the
attach is equal to the address of the nearest multiple of SHMLBA
(Lower Boundary Address).
shared memory : shmat()
 The third argument, shmflg, specifies the required shared memory
flag/s such as
 SHM_RND (rounding off address to SHMLBA) or
 SHM_EXEC (allows the contents of segment to be executed) or
 SHM_RDONLY (attaches the segment for read-only purpose, by
default it is read-write)
 This call would return the address of attached shared memory
segment on success and -1 in case of failure.
shared memory : shmdt()
 #include <sys/types.h>
 #include <sys/shm.h>
 int shmdt(const void *shmaddr)
 The above system call performs shared memory segment of detaching
the shared memory segment from the address space of the calling
process.
 The argument that needs to be passed is −
 The argument, shmaddr, is the address of shared memory segment to
be detached. The to-be-detached segment must be the address
returned by the shmat() system call.

 This call would return 0 on success and -1 in case of failure.


shared memory : shmctl()
 #include <sys/types.h>
 #include <sys/shm.h>
 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
 The above system call performs control operation for a shared
memory segment.
 The following arguments needs to be passed −
 The first argument, shmid, is the identifier of the shared memory
segment.
 The second argument, cmd, is the command to perform the
required control operation on the shared memory segment.
 Valid values for cmd are −
 IPC_STAT − Copies the information of the current values of each
member of struct shmid_ds to the passed structure pointed by buf.
This command requires read permission to the shared memory
segment.
shared memory : shmctl()
 IPC_SET − Sets the user ID, group ID of the owner, permissions, etc.
pointed to by structure buf.
 IPC_RMID − Marks the segment to be destroyed. The segment is
destroyed only after the last process has detached it.
 IPC_INFO − Returns the information about the shared memory
limits and parameters in the structure pointed by buf.
 SHM_INFO − Returns a shm_info structure containing information
about the consumed system resources by the shared memory.
 The third argument, buf, is a pointer to the shared memory
structure named struct shmid_ds.
 The values of this structure would be used for either set or get as per
cmd.
 This call returns the value depending upon the passed command. Upon
success of IPC_INFO and SHM_INFO or SHM_STAT returns the
index or identifier of the shared memory segment or 0 for other
operations and -1 in case of failure.
shared memory :program
 #include <iostream>
 #include <iostream>  #include <sys/ipc.h>
 #include <sys/ipc.h>  #include <sys/shm.h>
 #include <sys/shm.h>  #include <stdio.h>
 #include <stdio.h>  using namespace std;
 using namespace std;  int main()
 int main()  { // ftok to generate unique key
 { // ftok to generate unique key  key_t key = ftok("shmfile",65);
 key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid
 // shmget returns an identifier in shmid int shmid =
 int shmid = shmget(key,1024,0666|IPC_CREAT);
shmget(key,1024,0666|IPC_CREAT);  // shmat to attach to shared memory
 // shmat to attach to shared memory  char *str = (char*)
 char *str = (char*) shmat(shmid,(void*)0,0); shmat(shmid,(void*)0,0);
 printf("Data read from memory: %s\n",str);  cout<<"Write Data : ";
 //detach from shared memory  gets(str);
 shmdt(str); printf("Data written in memory: %s\n",str);
 // destroy the shared memory  //detach from shared memory
 shmctl(shmid,IPC_RMID,NULL);  shmdt(str);
 return 0; }  return 0; }
ipc status commands
 ipcs command shows information on the inter-process
communication facilities for which the calling process has read access.
By default, it shows information about all three resources:
 shared memory segments, message queues, and semaphore arrays.
Options :
 -q : Write information about active message queues.
 $ ipcs -q : It lists only message queues for which the current process
has read access.
-m : Write information about active shared memory segments.
 $ipcs -m : To lists the shared memories.
 -s : Write information about active semaphore sets.
 $ ipcs -s : To list the accessible semaphores.
 -a : Use all print options.
 $ ipcs -a : It provides details about message queue, semaphore and
shared memory.
ipc status commands
 -l : To get the limits for all three IPC facilities.
 $ipcs -l
 -c : Write creator’s user name and group name;
 $ ipcs -m -c : To list creator userid and groupid and owner userid and
group id.
 -o : Write information on outstanding usage. (Number of messages on
queue and total number of bytes in messages on queue for message
queues, and number of processes attached to shared memory
segments.)
 -p : Write process number information.
 $ ipcs -m -p : To displays creator id, and process id which accessed the
corresponding ipc facility very recently.
 -t : Write time information.
 $ ipcs -s -t : To get the last operation time in each ipc facility.
Socket:
Sockets: Are end-points for communication between processes. They
allow communication between a client program and a server program.
 An interface between application and network
◦ The application creates a socket
◦ The socket type dictates the style of communication
 reliable vs. best effort
 connection-oriented vs. connectionless
 Once configured the application can
◦ pass data to the socket for network transmission
◦ receive data from the socket (transmitted through the network by
some other host)
Socket:
 Internet-domain-specific sockets
 Several types of Internet socket are available:
 Sequential Packet Socket: This type of socket provides a reliable
connection for datagrams whose maximum length is fixed This
connection is two-way as well as sequenced.
 Datagram sockets, also known as connectionless sockets, which
use User Datagram Protocol (UDP).
 Stream sockets, also known as connection-oriented sockets, which
use Transmission Control Protocol (TCP), Stream Control
Transmission Protocol (SCTP) or Datagram Congestion Control
Protocol (DCCP).
 Raw sockets (or Raw IP sockets), typically available in routers and other
network equipment. Here the transport layer is bypassed, and the
packet headers are made accessible to the application.
Socket: Attributes
 Linux Sockets Detail attributes
Thresholds for this data set are associated with the Linux OS component.
 Node :The managed system name of the agent. The type is string (32
bytes long).
 Timestamp : The value is the time collected from the agent system
when the data row was built. It represents the local time zone of the
agent system. The type is timestamp.
 Socket Protocol :The sockets using this protocol. The type is integer
(32-bit numeric property) with enumerated values. The following values
are defined: TCP (0), UDP (1), RAW (2), UNIX (3), Not Available (-1),
Not Collected (-2).
 Receive Queue (Bytes)The count of bytes not copied by the user
program connected to this socket. The following values are valid:
integers.
Socket: Attributes
• Send Queue (Bytes)The count of bytes not acknowledged by the
remote host.

• Local Address The address of the local end of the socket, presented
as a dotted ip address. The type is string (16 bytes long).Local PortThe
local port number.

• Local Service Name: The local port number translated to service


name from /etc/services. The type is string (64 bytes long).

• Foreign Address :The address of the remote end of the socket. Like
"netstat" * indicates that the address is unassigned or unavailable.
Socket: Attributes
• Socket State:The state of the socket. The type is integer (32-bit
numeric property) with enumerated values.

• Socket UID: The user ID of the owner of the socket. The following
values are valid: integers.
• Socket Inode : The inode used by the socket.

• Foreign Port :The number of the foreign port.

• Socket Owner Name:The user name associated with the user ID


that owns or started the socket connection. The type is string (64
bytes long).
Socket: Addresses
• In Unix Socket Programming Various structures are used to hold
information about the address and port, and other information.
• Most socket functions require a pointer to a socket address structure
as an argument.
 The first structure is sockaddr that holds the socket information −
 struct sockaddr
 { unsigned short sa_family;
char sa_data[14]; };
 sa_family : AF_INET, AF_UNIX , AF_NS , AF_IMPLINK .

sa_data : Protocol-specific Address


Socket: Addresses
 The second structure is sockaddr_in that helps you to reference to
the socket's elements is as follows −
 struct sockaddr_in
 { short int sin_family;
 unsigned short int sin_port;
 struct in_addr sin_addr;
 unsigned char sin_zero[8]; };
 sin_family : AF_INET ,AF_UNIX , AF_NS, AF_IMPLINK
 sin_port: Service PortA 1[6-bit port number in Network Byte
Order].
 sin_addr : IP Address [A 32-bit IP address in Network Byte Order].
 sin_zero : Not Used
Socket: Addresses
in addr structure is used only in the above structure as a structure field
and holds 32 bit netid/hostid.
 struct in_addr { unsigned long s_addr; };
s_addr : service port [A 32-bit IP address in Network Byte Order].

 Hostent structure is used to keep information related to host.


 struct hostent { char *h_name; char **h_aliases; int h_addrtype; int
h_length; char **h_addr_list #define h_addr h_addr_list[0] };
 h_name : It is the official name of the host.
 h_aliases: It holds a list of host namealiases.
 h_addrtype: AF_INET It contains the address family.
 h_length : It holds the length of the IP address, 4 for Internet Address.
 h_addr_list: in_addr For Internet addresses, the array of pointers
h_addr_list[0], h_addr_list[1], and so on.
Socket: socket system call
The socket system call is used to obtain a socket descriptor on both the
client and the server.
Both these calls need not be synchronous or related in the time at which
they are called.
The synopsis is given below:
#include<sys/types.h>
#include<sys/socket.h>
int socket(int domain, int type, int protocol);

domain: integer, communication domain e.g., AF_INET (IPv4 protocol) ,


AF_INET6 (IPv6 protocol).
type: communication type
SOCK_STREAM: TCP(reliable, connection oriented)
SOCK_DGRAM: UDP(unreliable, connectionless).
protocol: Protocol value for Internet Protocol(IP), which is 0.
Socket: bind system call
Bind function binds the socket to the address and port number specified
in addr(custom data structure).
#include<sys/socket.h>
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
The bind system call requires the address family,(sockaddr )the port
number and the IP address.
The address family is known to be AF_INET, the IP address of the client
is already known to the operating system.
socklen_t addrlen : is the length of the socket address structure, the
pointer to which is the second argument.
Socket: Listen system call
Listen function puts the server socket in a passive mode, where it waits
for the client to approach the server to make a connection.
#include<sys/socket.h>
int listen(int sockfd, int backlog);
sockfd : is the socket descriptor of the socket on which the machine
should start listening.
backlog : is the maximum length of the queue for accepting
requests(connections).
If a connection request arrives when the queue is full, the client may
receive an error with an indication of ECONNREFUSED
Socket: connect system call
The connect() system call connects the socket referred to by the file
descriptor sockfd to the address specified by addr. Server’s address
and port is specified in addr.
#include<sys/socket.h>
#include<netinet/in.h> /* only for AF_INET , or the INET Domain */
int connect(int sockfd, struct sockaddr* addr, int addrlen);
Sockfd : is the same old socket descriptor.
Sockaddr Addr: is again the same kind of structure as used in
the bind system call.
Addrlen : is the length of the socket address structure, the pointer to
which is the second argument.
Socket: accept system call
The accept call is the mechanism by which the networking program on
the server receives that requests that have been accepted by the
operating system.
 #include<sys/socket.h>
 int accept(int sockfd, struct sockaddr* addr, int addrlen);
• sockfd : is the socket descriptor of the socket on which the machine
had performed a listen call and now desires to accept a request on that
socket.
• Addr: is the address structure that will be filled in by the operating
system by the port number and IP address of the client which has
made this request. This sockaddr pointer can be type-casted to
a sockaddr_in pointer for subsequent operations on it.
• Addrlen: is the length of the socket address structure, the pointer to
which is the second argument.
socket communications

Write about all


socket system
calls and read
,write system calls
socket communications
 Finally when both connect and accept return the connection has been
established.
 The socket descriptors that are with the server and the client can
now be used identically as a normal I/O descriptor.
 Both the read and the write calls can be performed on this socket
descriptor.
 The close call can be performed on this descriptor to close the
connection.
Variants of read and write also exist, which were specifically designed
for networking applications. These are recv and send.
 #include<sys/socket.h>
 int recv(int skfd, void *buf, int buflen, int flags);
 int send(int skfd, void *buf, int buflen, int flags);
 Except for the flags argument the rest is identical to the arguments of
the read and write calls. Possible values for the flags are:
socket Program
 copy from LP LAB record

Вам также может понравиться