Vits Np Manual

Embed Size (px)

Citation preview

  • 8/10/2019 Vits Np Manual

    1/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    Network Programming

    Introduction to Interprocess Communication

    Pipes

    Introduction%

    There are two types of pipes for two-way communication: anonymous pipes and namedpipes. Anonymous pipes enable related processes to transfer information to each other. Typically,an anonymous pipe is used for redirecting the standard input or output of a child process so that

    it can exchange data with its parent process. To exchange data in both directions (duplexoperation), you must create two anonymous pipes. The parent process writes data to one pipeusing its write handle, while the child process reads the data from that pipe using its read handle.Similarly, the child process writes data to the other pipe and the parent process reads from it.Anonymous pipes cannot be used oer a networ!, nor can they be used between unrelatedprocesses.

    Properties of Pipe:") #ipes do not hae a name. $or this reason, the processes must share a parent process. This is

    the main drawbac! to pipes. %oweer, pipes are treated as file descriptors, so the pipesremain open een after for! and exec.

    &) #ipes do not distinguish between messages' they ust read a fixed number of bytes. ewline(*n) can be used to separate messages. A structure with a length field can be used for messagecontaining binary data.

    +) #ipes can also be used to get the output of a command or to proide input to a command.

    &reation of ipes

    Since A pipe proides a one-way flow of data.nt pipe (int filedes)'

    nt pipefd&/' 0 pipefd1/ is opened for reading'pipefd"/ is opened for writing 0

    - " -

  • 8/10/2019 Vits Np Manual

    2/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    o after call to fork

    o after both calls to dup2

    - & -

  • 8/10/2019 Vits Np Manual

    3/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    o after all calls to close

    f the parent wants to receie data from the child, it should close fd", and the child should closefd1. f the parent wants to send data to the child, it should close fd1, and the child should closefd". Since descriptors are shared between the parent and child, we should always be sure to closethe end of pipe we aren2t concerned with. 3n a technical note, the 43$ will neer be returned ifthe unnecessary ends of the pipe are not explicitly closed.

    '(ample%

    4xample to show how to create and use a pipe:#include#include#include#include#include

    int main(void){ int fd2!" nbytes pid$t childpid

    char string! % &'ello" orld*n& char readbuffer+,!

    pipe(fd)

    if((childpid % fork()) %% -) { perror(&fork&) eit() 0

    - + -

  • 8/10/2019 Vits Np Manual

    4/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    if(childpid %% ,) { /1 hild process closes up input side of pipe 1/ close(fd,!)

    /1 3end &string& through the output side of pipe 1/ rite(fd!" string" (strlen(string)4)) eit(,) 0 else { /1 5arent process closes up output side of pipe 1/ close(fd!)

    /1 6ead in a string from the pipe 1/ nbytes % read(fd,!" readbuffer" si7eof(readbuffer)) printf(&6eceived string8 9s&" readbuffer) 0

    return(,)0

    '(ecution of rogram ) *esult%

    result:hello world

    read fd5+, write df 56

    Named Pipes

    Introduction

    amed pipes allow two unrelated processes to communicate with each other. They arealso !nown as $$3s (first-in, first-out) and can be used to establish a one-way (half-duplex)flow of data.

    amed pipes are identified by their access point, which is basically in a file !ept on the file

    system. 7ecause named pipes hae the pathname of a file associated with them, it is possible forunrelated processes to communicate with each other' in other words, two unrelated processes canopen the file associated with the named pipe and begin communication. 8nli!e anonymouspipes, which are process-persistent obects, named pipes are file system-persistent obects, thatis, they exist beyond the life of the process. They hae to be explicitly deleted by one of theprocesses by calling 9unlin!9 or else deleted from the file system ia the command line.

    - 6 -

  • 8/10/2019 Vits Np Manual

    5/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    n order to communicate by means of a named pipe, the processes hae to open the fileassociated with the named pipe. 7y opening the file for reading, the process has access to thereading end of the pipe, and by opening the file for writing, the process has access to the writingend of the pipe.

    A named pipe supports bloc!ed read and write operations by default: if a process opens the filefor reading, it is bloc!ed until another process opens the file for writing, and ice ersa.%oweer, it is possible to ma!e named pipes support non-bloc!ing operations by specifying the337;3

  • 8/10/2019 Vits Np Manual

    6/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    int mkfifo(const char *path, mode_t mode)

    The mkfifofunction ta!es the path of the file and the mode (permissions) with which the file

    should be created. t creates the new named pipe file as specified by the path.

    The function call assumes the 3ST if the named pipe already exists. The named pipe2s owner E is set tothe process2 effectie user E, and its group E is set to the process2 effectie group E, or if theSSFE bit is set in the parent directory, the group E of the named pipe is inherited from theparent directory.

    Opening a Named Pipe

    A named pipe can be opened for reading or writing, and it is handled ust li!e any other normalfile in the system. $or example, a named pipe can be opened by using the open()system call,

    or by using the fopen()standard < library function.

    As with normal files, if the call succeeds, you will get a file descriptor in the case of open(), or

    a 2$;42 structure pointer in the case of fopen(), which you may use either for reading or forwriting, depending on the parameters passed to open()or to fopen().

    Therefore, from a user2s point of iew, once you hae created the named pipe, you can treat it asa file so far as the operations for opening, reading, writing, and deleting are concerned.

    Reading From and Writing to a Named Pipe

    Ceading from and writing to a named pipe are ery similar to reading and writing from or to anormal file. The standard < library function calls read( )and write( )can be used for

    reading from and writing to a named pipe. These operations are bloc!ing, by default.

    The following points need to be !ept in mind while doing read0writes to a named pipe:

    A named pipe cannot be opened for both reading and writing. The process opening it

    must choose either read mode or write mode. The pipe opened in one mode will remain inthat mode until it is closed.

    Cead and write operations to a named pipe are bloc!ing, by default. Therefore if a

    process reads from a named pipe and if the pipe does not hae data in it, the reading processwill be bloc!ed. Similarly if a process tries to write to a named pipe that has no reader, thewriting process gets bloc!ed, until another process opens the named pipe for reading. This,of course, can be oerridden by specifying the 337;3

  • 8/10/2019 Vits Np Manual

    7/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    $or example, let us say you create the following named pipes:

    #" and #&

    n order to establish a full-duplex channel, here is how the serer and the client should treat thesetwo named pipes:

    ;et us assume that the serer opens the named pipe #" for reading and the second pipe #& forwriting. Then in order to ensure that this wor!s correctly, the client must open the first namedpipe #" for writing and the second named pipe #& for reading. This way a full-duplex channelcan be established between the two processes.

    $ailure to obsere the aboe-mentioned seHuence may result in a deadloc! situation.

    !enefits of Named Pipes

    amed pipes are ery simple to use.

    mkfifois a thread-safe function. o synchroniIation mechanism is needed when using named pipes.

    Jrite (using writefunction call) to a named pipe is guaranteed to be atomic. t is

    atomic een if the named pipe is opened in non-bloc!ing mode. amed pipes hae permissions (read and write) associated with them, unli!e anonymous

    pipes. These permissions can be used to enforce secure communication.

    "imitations of Named Pipes

    amed pipes can only be used for communication among processes on the same host

    machine. amed pipes can be created only in the local file system of the host, that is, you cannot

    create a named pipe on the $S file system. Eue to their basic bloc!ing nature of pipes, careful programming is reHuired for the client

    and serer, in order to aoid deadloc!s. amed pipe data is a byte stream, and no record identification exists.

    Code #amples

    The code samples gien here were compiled using the F8 < compiler ersion +.1.+ and wererun and tested on a S#AC< processor-based Sun 8ltra "1 wor!station running the Solaris K3perating 4nironment.

    The following code samples illustrate half-duplex and full-duplex communication between twounrelated processes by using named pipes.

    '(ample of alf-Duple( &ommunication

    - L -

  • 8/10/2019 Vits Np Manual

    8/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    n the following example, a client and serer use named pipes for one-way communication. Theserer creates a named pipe, opens it for reading and waits for input on the read end of the pipe.amed-pipe reads are bloc!ing by default, so the serer waits for the client to send some reHueston the pipe. 3nce data becomes aailable, it conerts the string to upper case and prints iaSTE38T.

    The client opens the same named pipe in write mode and writes a user-specified string to the pipe(see $igure ").

    The following table shows the contents of the header file used by both the client and serer. tcontains the definition of the named pipe that is used to communicate between the client and theserer.

    Filename : half_duplex.h

    #define':;$=5;?@ &/tmp/halfdupledefineA:@$B$3CD? 2EE

    Server CodeThe following table shows the contents of Filename : hd_server.c.

    #include#include#include#include#include#include#include#include &half$duple.h& /1 or name of the named-pipe 1/

    #include

    intmain(intargc" char1argv!){

    intfd" ret$val" count" numread charbufA:@$B$3CD?!

    /1 reate the named - pipe 1/

    - K -

  • 8/10/2019 Vits Np Manual

    9/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    ret$val % mkfifo(':;$=5;?@" ,FFF)

    if((ret$val %% -) GG (errno % ??@C3H)) { perror(&?rror creating the named pipe*n&) eit ()

    0

    /1 Ipen the pipe for reading 1/ fd % open(':;$=5;?@" I$6=IJ;K)

    /1 6ead from the pipe 1/ numread % read(fd" buf" A:@$B$3CD?)

    bufnumread! % L,L

    printf(&'alf =uple 3erver8 6ead rom the pipe 8 9s*n&"buf)

    /1 onvert to the string to upper case 1/ count % , hile(count < numread) { bufcount! % toupper(bufcount!) count44 0

    printf(&'alf =uple 3erver8 onverted 3tring 8 9s*n&" buf)0

    Client Code

    The following table shows the contents of Filename : hd_client.c

    #include#include#include#include#include#include#include#include

    #include&half$duple.h&/1 or name of the named-pipe 1/#include

    intmain(intargc" char1argv!){

    intfd

    /1 heck if an argument as specified. 1/

    - M -

  • 8/10/2019 Vits Np Manual

    10/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    if(argc % 2) { printf(&sage8 9sn&"argv,!) eit () 0

    /1 Ipen the pipe for riting 1/ fd % open(':;$=5;?@" I$M6IJ;K)

    /1 Mrite to the pipe 1/ rite(fd" argv!" strlen(argv!))

    0

    Running the Client and the ServerJhen you run the serer, it will bloc! on the read call and will wait until the client writessomething to the named pipe. After that it will print what it read from the pipe, conert the stringto upper case, and then terminate. n a typical implementation this serer will be either aniteratie or a concurrent serer. 7ut for simplicity and to demonstrate the communication throughthe named pipe, we hae !ept the serer code ery simple. Jhen you run the client, you willneed to gie a string as an argument.

    $irst compile the programs and sae the executable file as hdserer and hdclient respectiely.Na!e sure you run the serer first, so that the named pipe gets created.

    4xpected output:

    1. Cun the serer:

    % hd_server &

    The serer program will bloc! here, and the shell will return control to the command line.

    2. Cun the client:

    % hd_client hello

    3. The serer prints the string read and terminates:

    Half Duplex Server : Read From the pipe : hello

    Half Duplex Server : Converted String : HELLO

    '(ample of +ull-Duple( &ommunication

    - "1 -

  • 8/10/2019 Vits Np Manual

    11/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    n the following example, a client and serer use named pipes for two-way communication. Theserer creates two named pipes. t opens the first pipe for reading and the second pipe for writingto communicate bac! to the client. t then waits for input on the read pipe. 3nce data is aailable,it conerts the string to upper case and writes the conerted string to the write pipe, which theclient will read and print.

    The client opens the first pipe for writing, and it sends data through this pipe to the serer. Theclient opens the second pipe for reading, and through this pipe, it reads the serer2s response (see$igure &).

    The following table shows the contents of the header file used by both the client and serer. tcontains the definition of the two named pipes that are used to communicate between the clientand the serer.

    Filename : fullduplex.h

    #defineJ5 &/tmp/npdefineJ52 &/tmp/np2defineA:@$B$3CD? 2EE

    Server Code

    The following table shows the contents of Filename : fd_server.c

    #include#include#include#include#include#include#include&fullduple.h&/1 or name of the named-pipe 1/

    #include#include

    intmain(intargc" char1argv!){ intrdfd" rfd" ret$val" count" numread charbufA:@$B$3CD?!

    - "" -

  • 8/10/2019 Vits Np Manual

    12/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    /1 reate the first named - pipe 1/ ret$val % mkfifo(J5" ,FFF)

    if((ret$val %% -) GG (errno % ??@C3H)) { perror(&?rror creating the named pipe&)

    eit () 0

    ret$val % mkfifo(J52" ,FFF)

    if((ret$val %% -) GG (errno % ??@C3H)) { perror(&?rror creating the named pipe&) eit () 0

    /1 Ipen the first named pipe for reading 1/ rdfd % open(J5" I$6=IJ;K)

    /1 Ipen the second named pipe for riting 1/ rfd % open(J52" I$M6IJ;K)

    /1 6ead from the first pipe 1/ numread % read(rdfd" buf" A:@$B$3CD?)

    bufnumread! % L,L

    printf(&ull =uple 3erver86ead rom the pipe8 9s*n&" buf)

    /1 onvert to the string to upper case 1/ count % , hile(count < numread) { bufcount! % toupper(bufcount!) count44 0

    /11 1 Mrite the converted string back to the second1 1 pipe1 1/

    rite(rfd" buf" strlen(buf))0

    - "& -

  • 8/10/2019 Vits Np Manual

    13/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    Client Code

    The following program shows the contents of Filename : hd_client.c.

    #include#include#include#include#include#include#include&fullduple.h&/1 or name of the named-pipe 1/#include#include

    intmain(intargc" char1argv!)

    { intrfd" rdfd" numread charrdbufA:@$B$3CD?!

    /1 heck if an argument as specified. 1/

    if(argc % 2) {

    printf(&sage89sn&"argv,!) eit () 0

    /1 Ipen the first named pipe for riting 1/ rfd % open(J5" I$M6IJ;K)

    /1 Ipen the second named pipe for reading 1/ rdfd % open(J52" I$6=IJ;K)

    /1 Mrite to the pipe 1/ rite(rfd" argv!" strlen(argv!))

    /1 6ead from the pipe 1/

    numread % read(rdfd" rdbuf" A:@$B$3CD?)

    rdbufnumread! % L,L

    printf(&ull =uple lient86ead rom the 5ipe 8 9s*n&"rdbuf)0

    - "+ -

  • 8/10/2019 Vits Np Manual

    14/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    Running the Client and the ServerJhen you run the serer, it will create the two named pipes and will bloc! on the read

    call. t will wait until the client writes something to the named pipe. After that it will conert thestring to upper case and then write it to the other pipe, which will be read by the client and

    displayed on STE38T. Jhen you run the client you will need to gie a string as an argument.

    $irst compile the programs and sae the executable file as fdserer and fdclient respectiely.Na!e sure you run the serer first, so that the named pipe gets created.

    4xpected output:

    1. Cun the serer:

    % fd_server &

    The serer program will bloc! here, and the shell will return control to the command line.

    2. Cun the client:

    % fd_client hello

    The client program will send the string to serer and bloc! on the read to await the serer2sresponse.

    3. The serer prints the following:

    Full Duplex Server : Read From the pipe : hello

    The client prints the following:

    Full Duplex Client : Read From the pipe : HELLO

    - "6 -

  • 8/10/2019 Vits Np Manual

    15/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    .essage /ueue

    IntroductionProcesses that the UNIX kernel manages operate autonomously, which leads to a more

    stable system. However, every developer eventually runs into a situation where onegroup of processes needs to talk to another group of processes, perhaps to echangedata or send commands. !his communication is called Inter-ProcessCommunication"IPC#. !he $ystem % "$ys%# UNIX specification describes these threemechanisms for IP&, collectively referred to as $ys% IP&'

    (essage )ueues

    $emaphores

    $hared memory

    nderstanding t$e #%s& model

    !he three $ys% IP& methods have similar synta despite their different purposes. Ingeneral, do the following'

    *. +etermine the proper IP& key to use with ftok(N).

    . -et the IP&specific identifier associated with the IP& keyusing msgget(2), semget(2), or shmget(2)for message )ueues,

    semaphores, or shared memory, respectively.

    /. (odify attributes of the IP& instance with msgctl(2), semctl(2),

    or shmctl(2).

    0. (ake use of the specific IP& instance.

    1. 2t the end, destroy the IP& instance with msgctl(2), semctl(2),

    or shmctl(2)and the C5$6AC=flag.

    3ach instance of an IP& is given an identifier to distinguish it from other instances of theIP& that eist on the system. 4or eample, two different applications might each decideto use shared memory segments, so the systemwide IP& I+ distinguishes between thetwo instances. It might not be immediately obvious, but the first challenge is to figure outhow to distribute the information regarding how to attach to a common IP& instancewithout having an IP& mechanism in the first place.

    !he ftoklibrary call uses inode information from a given file and a uni)ue identifier tocome up with a key that stays the same as long as the file eists and the identifier isconstant. !hus, two processes could use their configuration files and compiletimeconstants to come up with the same IP& key. !he presence of the constant allows thesame application to create multiple instances of an IP& mechanism by varying theconstant.

    - "B -

  • 8/10/2019 Vits Np Manual

    16/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    5nce a set of processes have independently come up with their IP& keys, they mustthen get a specific identifier associated with the particular IP& instance using one ofthe getsystem calls. !he getcalls all re)uire the IP& key and a set of flags, as well as

    some si6e information for semaphores and shared memory. 7ecause UNIX is a

    multiuser system, the flags include file permissions in the familiar octal format "so 888means anyone can read and write#. If the C5$6?:Hflag is also set, the IP& instance

    will be created if it does not eist. If the C5$6?:Hflag is not set and the IP& instance

    has not been created, the getcall returns an error.

    2 simpler way to distribute the IP& instance identifier eists for those applications withthe capability to do so themselves. If you use a key of C5$56CO:H?when

    calling getto create the IP&, the instance identifier will be uni)ue. !he other processes

    that need to attach to the IP& do not need to call getbecause they already have the

    identifier.

    2pplications are free to use the IP& instances once they have the identifier. 3ach IP&method is different and is addressed in its own section.

    Passing messages t$roug$ 'ueues

    (essage )ueues provide a mechanism for one process to post a message that anotherprocess can pick up. 5nce the message is picked up, it is removed from the )ueue.(essage )ueues are uni)ue in that both processes do not have to eist simultaneously one process could post a message and eit, and the message could be picked updays later.

    (essages must consist of a long integer followed by the message data. 9isting *showssuch a structure in & using a *::byte message.

    "isting () C definition of a sample message

    struct mq_message { long type; /* The type or destination */ char text[100]; /* Data */;

    !he receiver of the message uses the message type. ;hen pulling a message from the)ueue, you can select the first available message or you can look for a particularmessage type. !he message types to use are applicationspecific, making )ueuesuni)ue from other forms of IP& in that the kernel has some understanding of theapplication data being passed by reading thetypefield.

    9isting shows the message submission part of message )ueuing.

    - "G -

    http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing1%23listing1http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing2%23listing2http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing2%23listing2http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing1%23listing1
  • 8/10/2019 Vits Np Manual

    17/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    * program t$at su+mits messages to a message 'ueue - ser,er

    The following program shows the contents of Filename : mg_server.c.

    #include#include#include#include#include

    intmain (void) {

    key$t ipckey

    intmP$id struct{ longtype chartet,,! 0 mymsg

    /1 Qenerate the ipc key 1/ ipckey % ftok(&/tmp/foo&" R2) printf(&Ay key is 9d*n&" ipckey)

    /1 3et up the message Pueue 1/ mP$id % msgget(ipckey" C5$6?:H S ,FFF) printf(&Aessage identifier is 9d*n&" mP$id)

    /1 3end a message 1/ memset(mymsg.tet" ," ,,) /1 lear out the space 1/ strcpy(mymsg.tet" &'ello" orld&) mymsg.type % msgsnd(mP$id" Gmymsg" si7eof(mymsg)" ,)

    0

    !he code in 9isting includes the necessary header files and then defines the variablesto be used within the mainfunction. !he first order of business is to determine the IP&

    key using /tmp/fooas the common file and the number 0 as the I+. 4or

    demonstration purposes, this key is displayed on the screen usingprintf(Nc)

    . Net,

    the message )ueue is created usingmsgget. !he first parameter to msggetis the IP&

    key, and the second is a set of flags. In the eample, the flags include the octalpermissions, which allow anyone with the IP& key to fully use this IP&, andthe C5$6?:Hflag, which causes msggetto create the )ueue. 2gain, the result is

    printed to the screen.$ending the message to the )ueue is simple. 2fter 6eroing out the memory space in themessage, a familiar string is copied to the tet part of the buffer. !he message type is

    - "L -

    http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing2%23listing2http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing2%23listing2
  • 8/10/2019 Vits Np Manual

    18/50

  • 8/10/2019 Vits Np Manual

    19/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    mP$client.cthen calls msgrcvto pull a message off the )ueue. !he first three

    arguments specify the message )ueue identifier, a pointer to the memory space that willhold the message, and the si6e of the buffer. !he fourth parameter is the typeparameter, and it allows you to be selective about which messages you get'

    If the type is :, the first message in the )ueue is returned.

    If the type is a positive integer, the first message in the )ueue with the same type

    is returned. If the type is a negative integer, the first message in the )ueue with the lowest

    value that is less than or e)ual to the absolute value of the specified type isreturned. 4or eample, if and then * were to be added to the )ueue,callingmsgrcvwith a type of would return the * because it is the smallest,

    even though it was second in the )ueue.

    !he fifth parameter to msgrcvis the blocking flag again. 9isting 0shows the client and

    server in action.

    Execution and result:

    sun!ox" #/mq_ser$er%y &ey is '0()(0++%essage identi,er is -sun!ox" #/mq_client%y &ey is '0()(0++%essage identi,er is -

    .ello orld 210(3

    !he output of the client and server show that they both came up with the same IP& keybecause they referenced the same file and identifier. !he server created the IP&instance, which the kernel assigned the value of , and the client application learnedthis. It should then come as no surprise that the client pulls =Hello, world>= back from themessage )ueue.

    !his eample shows the simplest of situations. 2 message )ueue would be helpful for ashortlived process such as a ;eb transaction that submits work to a heavier backendapplication such as some batch processing. 2 client can also be a server, and multiple

    applications can submit messages to the )ueue. !he message type field allowsapplications to direct messages to particular readers.

    Shared memory concept using Semaphores

    - "M -

    http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing4%23listing4http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing4%23listing4
  • 8/10/2019 Vits Np Manual

    20/50

  • 8/10/2019 Vits Np Manual

    21/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    00

    !he parameters to shmgetshould be familiar by now' key, si6e, and flags. !he si6e of

    the shared memory area in this eample is a single integer. 9isting ?differs fromprevious eamples in its use of C5$56CO:H?for the IP& key. ;hen C5$56CO:H?is

    used, a uni)ue IP& I+ is guaranteed to be created, and it is epected that theapplication distributes the I+ itself. In the eample, shmidis known by both the parent

    and child because they are copies of each other. !he forksystem call creates a

    second copy of the current process called the child process, which is virtually identicalto the parent. 3ecution of both processes resumes after the fork. !he return value is

    used to determine if the current process is the parent or child.

    7oth the parent and child look similar. 4irst, the shmatsystem call is used to get a

    pointer to the shared memory segment. shmatre)uires the shared memory I+, a

    pointer, and some flags. !he pointer is used to re)uest a particular address of memory.7y passing :, the kernel is free to choose whatever it wants. !he flags are mostlyvendorspecific, however 3'A$6=IJ;Kis a common flag that indicates the segment not

    written to. 2s shown in9isting ?, the common usage of shmatis to let the kernel decide

    everything.

    shmatreturns a pointer to the shared memory segment, which for debugging purposes

    is printed to the screen. 3ach process then takes a turn modifying the shared memorysegment and printing out the value. 4inally, the parent process removes the sharedmemory segment using shmctl(2).9isting @shows the output of this program.

    xecution and Result:

    sun!ox" #/shared_memory4hild pointer 56+00004hild $alue718arent pointer 56900008arent $alue718arent $alue7(-4hild $alue7(-

    Aou can see the sharing of the same memory space from the output. 4irst, the value inthe shared memory is *, which the child set and the parents read. !hen the parent setthe value to 0, which the child read. Note how the parent and child processes had adifferent pointer address to the shared memory segment, even though they wereaccessing the same physical memory. !his causes a problem for some data structures,such as linked lists, when the physical address is used, so you can use relativeaddressing if you are building comple structures in shared memory.

    - &" -

    http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing7%23listing7http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing7%23listing7http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing7%23listing7http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing8%23listing8http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing8%23listing8http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing7%23listing7http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing7%23listing7http://www.ibm.com/developerworks/aix/library/au-ipc/index.html#listing8%23listing8
  • 8/10/2019 Vits Np Manual

    22/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    !his eample relies on one process pausing while the other is writing to the sharedmemory segment. In a real application, this would not be practical, so if your applicationcould potentially have multiple processes writing to the same memory location, considerlocking that area with a semaphore.

    ConclusionUNIX provides several methods for IP&. !he $ys% IP& methods are message )ueues,semaphores, and shared memory. (essage )ueues allow one application to submit amessage that other applications can pick up later, even after the sending applicationhas finished. $emaphores ensure that multiple applications can lock resources andavoid race conditions. $hared memory allows multiple applications to share a commonsegment of memory, which provides a fast method of communicating and sharing largeamounts of data. Aou can also use these methods together. 4or eample, you can use asemaphore to control access to a shared memory segment.

    IP& methods are helpful to application developers because they provide a standard wayto communicate between applications and are portable across different UNIX flavors.!he net time you find yourself needing to lock resources or share data betweenprocesses, try the $ys% IP& mechanisms.

    TCP Iterative server program usingfork()

    ;rite a & program, using sockets create client and server socket programs. ;rite a

    !&P iterative server program, in server program take user input for port number and

    bind the port address. $erver waits for clients to connect. ;hen client connects

    communication can happen using recv and sent functions.

    4ollowing is the functionalities of server program'

    *. &lient sends message to server using sent functions.

    . $erver receives all the messages, server ignores all the consonants in the

    message.

    /. 2ll the vowels in the message are converted into upper case.

    0. $erver returns the entire message to clients "with toggled vowel cases#.

    1. 4or eample' =!his is a test and sample message.= to server will be sent back

    to client as = egassem elpmas dan tset a si sih!.=

    - && -

    http://exploreurtalents.blogspot.com/http://exploreurtalents.blogspot.com/http://exploreurtalents.blogspot.com/http://exploreurtalents.blogspot.com/
  • 8/10/2019 Vits Np Manual

    23/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    ;hen client closes the connection server should close the communication with that

    client "socket#. 2nd once again wait for new clients to connect. $erver program never

    eits.

    Using fork function rewrite the programs, such that this server can handle multiple client

    connections at one time. !o test this you need to run simultaneously multiple copies of

    client eecutions. Please log on server machine number of clients it is handled

    at t$istime.

    * server program *

    The following program shows the contents of Filename : TCP_server.c.

    #include #include #include #include #include #include #include #include #include #include #include

    #defineAK5I6H NEN /1Hhe port users ill be connecting to1/

    voidreadstring(int"char1)

    intmain(int" char1O! ){

    int listensocket"connectionsocket"retbindstruct sockaddr$in

    serveraddress"cliaddrsocklen$t len

    charbuf,,!"databuf,2R!

    listensocket % socket(:$CJ?H" 3IT$3H6?:A" , )if(listensocket < , ){

    perror(&socket&)eit()

    0

    - &+ -

  • 8/10/2019 Vits Np Manual

    24/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    memset(Gserveraddress" ," si7eof(serveraddress) )serveraddress.sin$family % :$CJ?Hserveraddress.sin$port % htons(AK5I6H)/15I6H JI1/serveraddress.sin$addr.s$addr %

    htonl(CJ:==6$:JK)/1:==6?331/

    retbind%bind(listensocket"(structsockaddr1)Gserveraddress"si7eof(serveraddress))/1heck the return value of bind for error1/if(-%%retbind){

    perror(&BCJ= ?66I6*n&)eit()

    0

    listen(listensocket"E)/1Beginning of the Aain 3erver 5rocessing ;oop1/

    for(){ printf(&3erver8C am aiting-----3tart of Aain ;oop*n&)

    len%si7eof(cliaddr)connectionsocket%accept(listensocket"

    (structsockaddr1)Gcliaddr"Glen)if(connectionsocket < ,){

    if(errno %% ?CJH6)printf(&Cnterrupted system call UU&)continue

    0printf(&onnection from 9s*n&"inet$ntop(:$CJ?H"Gcliaddr.sin$addr"buf"si7eof(buf)))

    readstring(connectionsocket " databuf) close(connectionsocket) printf(&inished 3erving Ine lient*n&)0

    0

    /11111111111111111111111111111111111111111111111111111111111

    1 JHCIJ J:A?8readstring1 =?36C5HCIJ8 6eads the string sent by the client over the1 socket and stores it in the array fname .1 JIH?3 8 Jo ?rror hecking is done .1 6?H6J3 8void11111111111111111111111111111111111111111111111111111111111/

    voidreadstring(

    - &6 -

  • 8/10/2019 Vits Np Manual

    25/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    intconnectionsocket" /13ocket =escriptor1/ char1fname) /1:rray " to be populated by the string from

    client1//11111111111111111111111111111111111111111111111111111111111/{

    intpointer%,"nintlen%,"a"bcharrevE,!"tempE,!"tempE,!

    intk"ihile((n%read(connectionsocket"(fname 4 pointer)",2R))>,){

    pointer%pointer4n0fnamepointer!%L*,L

    printf(&enter the string*n&)

    printf(&3erver 86eceived 9s*n &"fname)

    //strcpy(temp"fname)k%strlen(fname) // for(k%,tempk!%,k44) // len%ka%,for(i%k-i>%,i--)tempa44!%fnamei!tempa!%L*,L

    printf(&*nrev is 9s*n&" temp)

    0/11111111111111111111111111111111111111111111111111111111111/

    /* client */

    The following program shows the contents of Filename : TCP_client.c.

    #include #include #include #include #include #include #include #include

    - &B -

  • 8/10/2019 Vits Np Manual

    26/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    #include #include #include #defineA:@B?6 ,2Rvoidsendstring(int" char1)

    intmain( int" char1O! ){

    int sd"fdcharcstruct sockaddr$in serveraddresschartet,,!inti%,sd % socket( :$CJ?H" 3IT$3H6?:A" , )if( sd < , ) {

    perror( &socket&)eit( )

    0if(O! %% J;; ) {printf (&5; specfiy the serverLs C5 :ddress *n&)eit(,)0if(O2! %% J;; ) {printf (&5; specify the serverLs 5ort Jo *n&)eit(,)0memset( Gserveraddress" ," si7eof(serveraddress) )serveraddress.sin$family % :$CJ?H

    serveraddress.sin$port % htons(atoi(O2!))//5I6H JIserveraddress.sin$addr.s$addr % inet$addr(O!)//:==6?33if(connect(sd"(structsockaddr1)Gserveraddress"

    si7eof(serveraddress))

  • 8/10/2019 Vits Np Manual

    27/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    close(sd)return,

    0/11111111111111111111111111111111111111111111111111111111111 JHCIJ J:A?8sendstring

    1 =?36C5HCIJ8 sends a string over the socket .1 JIH?3 8 Jo ?rror hecking is done .1 6?H6J3 8void11111111111111111111111111111111111111111111111111111111111/

    voidsendstring(intsd" /13ocket =escriptor1/ char1fname) /1:rray ontaining the string 1/

    /1111111111111111111111111111111111111111111111111111111111/{ intn " bytesritten%, " ritten

    charbufferA:@B?6!strcpy(buffer " fname)n%strlen(buffer)hile(bytesritten

  • 8/10/2019 Vits Np Manual

    28/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    userVlocalhost eekW!X cc tcpclient.cuserVlocalhost eekW!X mv a.out tcpclientuserVlocalhost eekW!X./tcpclient 2Y.,.,. NENenter sentence to end enter #Jetork 5rogramming#3tring 8 Jetork 5rogramming sent to server

    T& concurrent ser0er to con0ert a gi0en te(t into upper case using

    multiple(ing system call select!

    Theselect()andpoll()methods can be a powerful tool when youOre multiplexing networ!soc!ets. Specifically, these methods will indicate when a procedure will be safe to execute on anopen file descriptor without any delays. $or instance, a programmer can use these calls to !now

    when there is data to be read on a soc!et. 7y delegating responsibility toselect()andpoll(), youdonOt hae to constantly chec! whether there is data to be read. nstead,select()andpoll()can beplaced in the bac!ground by the operating system and wo!en up when the eent is satisfied or aspecified timeout has elapsed. This process can significantly increase execution efficiency of aprogram. (f you are more concerned with performance than portability, we discuss somealternaties toselect()andpoll()toward the end of the article.)

    select 2 description

    The Single 8> Specification, ersion & (S8S&) definesselect()as follows:int select(int nfds, fdset readfds, fdset writefds, fdset errorfds, struct timeal timeout)'

    t ta!es these parameters:

    P int nfds- The highest file descriptor in all gien sets plus one

    P fd_set *readfds- $ile descriptors that will trigger a return when data is ready to be read

    P fd_set *writefds- $ile descriptors that will trigger a return when data is ready to be written to

    P fd_set *errorfds- $ile descriptors that will trigger a return when an exception occurs

    P struct timeval *timeout- The maximum periodselect()should wait for an eent

    The return alue indicates the number of file descriptors (fds) whose reHuest eent has beensatisfied.

    @ou canOt modify thefd_setstructure by changing its alue directly. The only portable way toeither set or retriee the alue is by using the proidedFD_*macros:

    P FD_ZERO(fd_set *)- nitialiIes anfd_setto be empty

    P FD_CLR(int fd, fd_set *)- Cemoes the associated fd from thefd_set

    P FD_E!(int fd, fd_set *)- Adds the associated fd to thefd_set

    P FD_"E!(int fd, fd_set *)- Ceturns a nonIero alue if the fd is infd_set

    - &K -

    http://www.opengroup.org/onlinepubs/007908799/xsh/select.htmlhttp://www.opengroup.org/onlinepubs/007908799/xsh/select.htmlhttp://www.opengroup.org/onlinepubs/007908799/xsh/select.html
  • 8/10/2019 Vits Np Manual

    29/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    8pon return fromselect(),FD_"E!()can be called for each fd in a gien set to identifywhether its condition has been met.

    Jith the timeoutalue, you can specify how longselect()will wait for an eent.

    ftimeoutis#$LL,select()will wait indefinitely for an eent. f timeout2s timevalstructures areset to 1,select()will return immediately rather than wait for any eent to occur.3therwise, timeoutdefines how longselect()will wait.

    34T& S'*V'*5S','&T43

    #include #include #include #include #include

    #include #include #include #include #include #include #include #include #defineA:@;CJ? ,,#define3?6O$5I6H NEN

    intmain(intargc" char11argv){

    int k" i" mai" mafd" listenfd" connfd" sockfdint nready" client=$3?H3CD?!ssi7e$t nfd$set rset" allsetchar lineA:@;CJ?!"buf,,!socklen$t clilenstructsockaddr$in cliaddr" servaddr

    listenfd % socket(:$CJ?H" 3IT$3H6?:A" ,)if(listenfd < , )

    {perror(&socket&)eit()

    0b7ero(Gservaddr" si7eof(servaddr))servaddr.sin$family % :$CJ?Hservaddr.sin$addr.s$addr % htonl(CJ:==6$:JK)servaddr.sin$port % htons(3?6O$5I6H)

    - &M -

  • 8/10/2019 Vits Np Manual

    30/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    bind(listenfd" (structsockaddr 1) Gservaddr"si7eof(servaddr))

    listen(listenfd"E)

    mafd % listenfd /1 initiali7e 1/mai % - /1 inde into client!

    array 1/for(i % , i < =$3?H3CD? i44)

    clienti! % - /1 - indicates availableentry 1/

    =$D?6I(Gallset)=$3?H(listenfd" Gallset)

    /1 end fig, 1/

    /1 include fig,2 1/for( ) {

    printf(&3erver8C am aiting-----3tart of Aain ;oop*n&)rset % allset /1 structure assignment 1/nready % select(mafd4" Grset" J;;" J;;" J;;)

    if(=$C33?H(listenfd" Grset)) {/1 ne client connection 1/clilen % si7eof(cliaddr)connfd % accept(listenfd" (structsockaddr 1)

    Gcliaddr" Gclilen)

    #ifdef JIH=?printf(&ne client8 9s" port 9d*n&"inet$ntop(:$CJ?H"

    Gcliaddr.sin$addr" buf" J;;)"ntohs(cliaddr.sin$port))#endif

    for(i % , i < =$3?H3CD? i44)if(clienti! < ,) {

    clienti! % connfd /1 save descriptor1/

    break0

    if(i %% =$3?H3CD?) { printf(&too many clients&) eit(,) 0

    =$3?H(connfd" Gallset)/1 add ne descriptor to set 1/

    - +1 -

  • 8/10/2019 Vits Np Manual

    31/50

  • 8/10/2019 Vits Np Manual

    32/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    1 =?36C5HCIJ8ontains ode for a client that ill send astring1 to a server process and eits.1 Cnvoke the ?ecutable as a.out C5:ddress 5ortJo string1 opyright 2,,Y :ricent

    111111111111111111111111111111111111111111111111111111111111/#include #include #include #include #include #include #include #include #include #include #include #defineA:@B?6 ,2Rvoidsendstring(int" char1)

    intmain( int" char1O! ){

    int sd"fdcharc

    struct sockaddr$in serveraddresschartet,,!

    inti%,sd % socket( :$CJ?H" 3IT$3H6?:A" , )

    if( sd < , ) {perror( &socket&)eit( )

    0if(O! %% J;; ) {printf (&5; specfiy the serverLs C5 :ddress *n&)eit(,)0if(O2! %% J;; ) {printf (&5; specify the serverLs 5ort Jo *n&)eit(,)

    0memset( Gserveraddress" ," si7eof(serveraddress) )serveraddress.sin$family % :$CJ?Hserveraddress.sin$port % htons(atoi(O2!))//5I6H JIserveraddress.sin$addr.s$addr % inet$addr(O!)//:==6?33if(connect(sd"(structsockaddr1)Gserveraddress"

    si7eof(serveraddress))

  • 8/10/2019 Vits Np Manual

    33/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    printf(&annot onnect to server&)eit()

    0printf(&enter sentence to end enter #&)hile()

    {c%getchar()if(c%%L#L)breakteti44!%c0teti!%L*,L

    sendstring(sd"tet)close(sd)return,

    0/111111111111111111111111111111111111111111111111111111111111 JHCIJ J:A?8sendstring1 =?36C5HCIJ8 sends a string over the socket .1 JIH?3 8 Jo ?rror hecking is done .1 6?H6J3 8void1111111111111111111111111111111111111111111111111111111111/

    voidsendstring(intsd" /13ocket =escriptor1/ char1fname) /1:rray ontaining the string 1/

    /11111111111111111111111111111111111111111111111111111111111/

    { intn " bytesritten%, " ritten charbufferA:@B?6!strcpy(buffer " fname)n%strlen(buffer)hile(bytesritten

  • 8/10/2019 Vits Np Manual

    34/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    rootVlocalhost eekYand+!# cc tcpservselect,.crootVlocalhost eekYand+!# mv a.out tcpservselectrootVlocalhost eekYand+!# ./tcpservselectbash8 ./tcpservselect8 Jo such file or directory

    Kou have ne mail in /var/spool/mail/rootrootVlocalhost eekYand+!# ./tcpservselect3erver8C am aiting-----3tart of Aain ;oop3erver8C am aiting-----3tart of Aain ;oop

    output at server: B =3erver8C am aiting-----3tart of Aain ;oop

    output at server: B =3erver8C am aiting-----3tart of Aain ;oop3erver8C am aiting-----3tart of Aain ;oop

    Compiling and running Client.

    rootVlocalhost eekYand+!# ./tcpclient 2Y.,.,. NENenter sentence to end enter #abcd#3tring 8 abcd sent to server

    T& concurrent ser0er to echo gi0en set of sentences using poll functions

    poll2 description

    Thepoll()method attempts to consolidate the arguments ofselect()and proides notification of awider range of eents. The S8S& definespoll()as follows:

    int poll(struct pollfd fds /, nfdst nfds, int timeout)'

    t ta!es these parameters:

    P struct pollfd fds% &- An array ofpollfdstructures

    P nfds_t nfds- The number of file descriptors set infds% &

    P int timeout- %ow longpoll()should wait for an eent to occur (in milliseconds)

    The return alue indicates how many fds had an eent occur.

    Apollfdstruct typically includes the following members:

    P int fd- ndicates which fd to monitor for an eent

    P s'ort events- A bitwise field that represents which eents will be monitored

    P s'ort revents- A bitwise field that represents which eents were detected in a call topoll()

    - +6 -

    http://www.opengroup.org/onlinepubs/007908799/xsh/poll.htmlhttp://www.opengroup.org/onlinepubs/007908799/xsh/poll.html
  • 8/10/2019 Vits Np Manual

    35/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    rogram

    T

  • 8/10/2019 Vits Np Manual

    36/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    client,!.events % 5I;;6=JI6Afor(i % i < I5?J$A:@ i44)

    clienti!.fd % -/1 - indicates available entry 1/

    mai % -

    /1 ma inde into client! array 1//1 end fig, 1/

    /1 include fig,2 1/

    for( ) {

    nready % poll(client" mai4" CJHCA)

    if(client,!.revents G 5I;;6=JI6A) {/1 ne client connection 1/clilen % si7eof(cliaddr)connfd % accept(listenfd" (structsockaddr 1)

    Gcliaddr" Gclilen)#ifdef JIH=?

    printf(&ne client8 9s*n&" sock$ntop((structsockaddr 1) Gcliaddr" clilen))

    #endif

    for(i % i < I5?J$A:@ i44)if(clienti!.fd < ,) {

    clienti!.fd % connfd/1 save descriptor 1/

    break0

    if(i %% I5?J$A:@){

    printf(&too many clients&)eit(,)

    0

    clienti!.events % 5I;;6=JI6Aif(i > mai)

    mai % i

    /1 ma inde in client! array 1/

    if(--nready

  • 8/10/2019 Vits Np Manual

    37/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    /1 check all clients for data 1/if( (sockfd % clienti!.fd) < ,)

    continueif(clienti!.revents G (5I;;6=JI6A S 5I;;?66)) {

    if( (n % read(sockfd" line" A:@;CJ?)) < ,) {

    if(errno %% ?IJJ6?3?H) {/1Rconnection reset by client 1/#ifdef JIH=?

    printf(&client9d! aborted connection*n&" i)#endif

    close(sockfd)clienti!.fd % -

    0 elseprintf(&readline error&)

    0 elseif(n %% ,) {/1Rconnection closed by client 1/

    #ifdef JIH=?printf(&client9d! closed connection*n&" i)

    #endifclose(sockfd)clienti!.fd % -

    0 else{printf(&*n data from client is *n&)

    printf(& data % 9s*n&"line)

    //rite(sockfd" line" n)

    strcpy(line"& &)0

    if(--nready

  • 8/10/2019 Vits Np Manual

    38/50

  • 8/10/2019 Vits Np Manual

    39/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    The User Datagram Protocol

    Introduction%

    The T

  • 8/10/2019 Vits Np Manual

    40/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    UDP Datagram Format

    8E# proides a way for applications to send encapsulated # datagram without haing toestablish a connection. 8E# transmitssementsconsisting of an K-byte header followed by thepayload. The format is shown in $igure

    7D header

    The O$RCE /OR!field identifies the $D/ processwhich sent the datagram.

    TheDE!"#!"O# /OR!field identifies the $D/ processthat will handle the payload.

    The E0E LE#0!1field includes the K-byte header and the data, measured on

    octets. The C1EC2$field is optional and stored as Iero if not computed (a computed Iero is

    stored as all ones).

    ote that 8E# does not proide flow control, error control, or retransmission on receipt of a bad

    segment. All it proides is demultiplexing multiple processes using the port numbers.

    .$e DP C$ecksum

    The "G-bit C1EC2$field is optional. The sender can choose to compute a chec!sum or setthe field to Iero. The receier only erifies the chec!sum if the alue is non-Iero. ote that 8E#uses ones-complement arithmetic, so a computed Iero alue is stored as all-ones.

    UDP Problems

    Since 8E# proides only a simple deliery serice, almost all of the problems with 8E# are

    related to deliery problems.

    8E#-based applications are prone to failures in a congested or loss-intensie networ!

    because a lost 8E# datagram has to be handled by the application.

    As an extreme example, consider the etwor! $ile System ($S) which uses 8E# for

    remote file system access, since it benefits from the low-oerhead nature of 8E#. $Stypically writes data in large chun!s (often K =7 bloc!s), which are then split into #fragments depending on the NT8 of the underlying topology.

    - 61 -

  • 8/10/2019 Vits Np Manual

    41/50

  • 8/10/2019 Vits Np Manual

    42/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    {printf(&5lease enter the 5ort Jumber of the

    server*n&)eit(,)

    0

    sd % socket( :$CJ?H" 3IT$=Q6:A" , )if( sd < , ){

    perror( &socket&)eit( )

    0

    memset( Gserveraddress" ," si7eof(serveraddress) )serveraddress.sin$family % :$CJ?Hserveraddress.sin$port % htons(atoi(argv2!))

    //5I6H JIserveraddress.sin$addr.s$addr % inet$addr(argv!)

    //:==6?33

    printf(&lient 3tarting service*n&)printf(&?nter =ata or the server*n&)str$cli(stdin"sd "(structsockaddr 1)Gserveraddress"

    si7eof(serveraddress))0

    /1111111111111111111111111111111111111111111111111111111

    1 JHCIJ J:A?8sig$usr1 =?36C5HCIJ8 3ignal 'andler for Hrappinf 3CQ5C5?1 JIH?3 8 Jo ?rror hecking is done .1 6?H6J3 8void111111111111111111111111111111111111111111111111111111111/staticvoidsig$usr(

    intsigno) /13ignal Jumber1//11111111111111111111111111111111111111111111111111111111/{

    char1strpipe%&6??CO?= 3CQ5C5? - ?66I6&char1strctrl%&6??CO?= H6;- 6IA KI&

    if(signo%%3CQ5C5?){

    rite("strpipe"strlen(strpipe))eit()

    0elseif(signo%%3CQCJH){

    rite("strctrl"strlen(strctrl))

    - 6& -

  • 8/10/2019 Vits Np Manual

    43/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    eit()0

    0

    /11111111111111111111111111111111111111111111111111111111 JHCIJ J:A?8str$cli1 =?36C5HCIJ8 Aain lient 5rocessing (3elect aits for

    readiness of1 connection socket or stdin1 JIH?3 8 Jo ?rror hecking is done .1 6?H6J3 8void111111111111111111111111111111111111111111111111111111111/

    voidstr$cli(C;? 1fp"/1'ere to be used as stdin as argument1/

    intsockfd "structsockaddr 1to "socklen$t length)

    /1onnection 3ocket 1//111111111111111111111111111111111111111111111111111111/{

    intmades"nfd$set rsetcharsendbufB3CD?! " recvbufB3CD?! "servername,,!structsockaddr$in serveraddrsocklen$t slen=$D?6I(Grset)mades%(sockfd>fileno(fp)Usockfd48fileno(fp)4)

    for(){=$3?H(fileno(fp) " Grset)=$3?H(sockfd " Grset)select(mades"Grset"J;;"J;;"J;;)if(=$C33?H(sockfd " G rset)){

    slen%si7eof(serveraddr)n%recvfrom(sockfd"recvbuf"B3CD?","

    (structsockaddr1)Gserveraddr"Gslen)printf(&=ata 6eceived from server 9s8*n&"

    inet$ntop(:$CJ?H"Gserveraddr.sin$addr"servername"si7eof(servername)))

    rite("recvbuf"n)printf(&?nter =ata or the server*n&)

    0if(=$C33?H(fileno(fp) " G rset))

    - 6+ -

  • 8/10/2019 Vits Np Manual

    44/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    {/16eading data from the keyboard1/fgets(sendbuf"B3CD?"fp)n % strlen (sendbuf)/13ending the read data over socket1/

    sendto(sockfd"sendbuf"n","to"length)printf(&=ata 3ent Ho 3erver*n&)0

    0

    0/1111111111111111111111111111111111111111111111111111111/

    0Serer0

    The following program shows the contents of Filename : udp_server.c.

    #include #include #include #include #include #include #include #include

    #include #include #include

    #defineB3CD? E2#defineAK5I6H Y,#defineA:@J:A? ,,

    intmain(int" char11O )

    { int sd"n"retstruct sockaddr$in

    serveraddress"cliaddrsocklen$t lengthcharclientnameA:@J:A?!"datareceivedB3CD?!chartempE,!"arevE,!"tempE,!intlen"k"a

    - 66 -

  • 8/10/2019 Vits Np Manual

    45/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    sd % socket( :$CJ?H" 3IT$=Q6:A" , )if( sd < , ) {

    perror( &socket&)eit( )

    0

    memset( Gserveraddress" ," si7eof(serveraddress) )memset( Gcliaddr" ," si7eof(cliaddr) )serveraddress.sin$family % :$CJ?Hserveraddress.sin$port % htons(AK5I6H)

    //5I6H JIserveraddress.sin$addr.s$addr % htonl(CJ:==6$:JK)

    //C5 :==6?33ret%bind(sd"(struct

    sockaddr1)Gserveraddress"si7eof(serveraddress))if(ret

  • 8/10/2019 Vits Np Manual

    46/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    (structsockaddr1)Gcliaddr"length)0

    0

    '(ecution ) result %

    Compiling and running server.

    userVlocalhost eekW!X cc udp$server.cuserVlocalhost eekW!X mv a.out udp$serveruserVlocalhost eekW!X ./ udp$serverC am aiting=ata 6eceived from 2Y.,.,.C have received abcd efgh

    rev ishgfe dcbaC am aiting

    Compiling and running client.

    userVlocalhost eekW!X cc udp$client.cuserVlocalhost eekW!X mv a.out udp$client

    userVlocalhost eekW!X ./ udp$client 2Y.,.,. Y,lient 3tarting service?nter =ata or the serverabcd efgh=ata 3ent Ho 3erver=ata 6eceived from server 2Y.,.,.8abcd efgh?nter =ata or the server

    - 6G -

  • 8/10/2019 Vits Np Manual

    47/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    Cemote #rocedure

  • 8/10/2019 Vits Np Manual

    48/50

    Vignan Institute of Technology and Science - Deshmukhi

    1 Day Workshop on Network rogramming! "nd #uly "$11

    rograms%Design a *& application to pass a simple 0aria;le through *& connection