Network Lab Manual 2

Embed Size (px)

Citation preview

  • 8/9/2019 Network Lab Manual 2

    1/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    List of Experiments (as per syllabus):

    Expt.

    No Name of the Experiment

    No. of 

    Periods

    Cumulative No.

    Of periods

    CYCLE I

    1 Basic unix commands and introduction tovi editor.

    3 3

    2 Introduction to socket programming.Socket Creation & Binding the socket

    3 6

    3 Develop a server using socket with listen,accept and send/receive system calls 3 9

    4 Develop a Client that contacts a givenDNS Server to resolve a given host name. 3 12

    5 Develop a Client – Server application for chat. 3 15

    6 Write a Client to download a file from aHTTP Server. 3 18

    7Study of Network Simulators like

     NS2/Glomosim / OPNET.Introduction to Ns2

    3 21

    8 Simple programs using NS2 3 24

    Model Exam – I 3 27

    CYCLE II

    9Simulation of protocols such asARP/RARP

    3 30

    10Write a program that takes a binary file asinput and performs bit stuffing and CRCCom utation.

    3 33

    10 Develop an application for transferringfiles over RS232. 3 36

    11 Simulation of Sliding-Window protocol. 3 39

    12 Simulation of BGP / OSPF routing protocol. 3 42

    Model Exam – II 3 45

    Contemporary Experiments (beyond syllabus):

    Expt.

    No Name of the Experiment

    No. of 

    Periods

    Cumulative

    No.

    Of periods

    1 Study of LAN switch (CISCO 2950) 4 49

    2 Study of Routers (CISCO 2600) 4 53

    3 Study of crypt tools (Crypt tool, Ethereal) 4 57

    4 Study of Wireless LAN devices 3 60

    NETWORK LAB MANU AL

    http://csetube.co.nr/http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    2/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    Mini Projects:

    Simulation of congestion control in TCP using NS-2

    Simulation of Traffic Engineering using NS-2

    Simulation of Policy based networks using NS-2

    Reference web sites:

    http://www.linuxhq.org

    http://www1.us.elsevierhealth.com

    www.ipv6.org

    www.dbaseiv.net/socketsfaq.html

    www.dbaseiv.net/sockets/beej/net/

    www.protocols.com/pbook/tcpip.html

    http://www.ecst.csuchico.edu/~chafey/prog/sockets/sinfo1.html

    http://www.uwo.ca/its/doc/courses/notes/socket/

    http://www.tldp.org/guides.html http://www.linuxgazette.com/issue47/bueno.html

    ftp://gaia.cs.umass.edu/cs653_1996/sock.ps

    http://www-net.cs.umass.edu/ntu_socket/

    http://www.geocities.com/kollurihari/hari/harilinks.html

    http://www.fortunecity.com/skyscraper/arpanet/6/cc.htm

    http://www.cs.buffalo.edu/~milun/unix.programming.html

    http://www.coding-zone.co.uk/cpp/articles/140101networkprogrammingc.shtml

    http://beej.us/guide/bgnet/

    http://orca.st.usm.edu/~seyfarth/network_pgm/homework1.html

    http://www.cs.rpi.edu/courses/netprog/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    3/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    1. Introduction to VI Editor

    The VI editor is a screen-based editor used by many Unix users. The VI editor has powerffeatures to aid programmers, but many beginning users avoid using VI because the differe

    features overwhelm them. This tutorial is written to help beginning users get accustomed to usinthe VI editor, but also contains sections relevant to regular users of VI as well. Examples a

     provided, and the best way to learn is to try these examples, and think of your own examples well... There's no better way than to experience things yourself.

    1.1 Starting the VI Editor 

    The VI editor lets a user create new files or edit existing files. The command to start the VI edito

    is vi, followed by the filename. For example to edit a file called  temporary, you would type v

    temporary and then return. You can start VI without a filename, but when you want to save yowork, you will have to tell VI which filename to save it into later.

    When you start VI for the first time, you will see a screen filled with tildes (A tilde looks like thi~) on the left side of the screen. Any blank lines beyond the end of the file are shown this way. Athe bottom of your screen, the filename should be shown, if you specified an existing file, and thsize of the file will be shown as well, like this:

    "filename" 21 lines, 385 charactersIf the file you specified does not exist, then it will tell you that it is a new file, like this:"newfile" [New file]If you started VI without a filename, the bottom line of the screen will just be blank when VI startIf the screen does not show you these expected results, your terminal type may be set wrong. Ju

    type : q and return to get out of VI.

    1.2 The Two Modes of VI 

    The first thing most users learn about the VI editor is that it has two modes:  command and inserThe   command  mode allows the entry of commands to manipulate text. These commands ausually one or two characters long, and can be entered with few keystrokes. The  insert mode puanything typed on the keyboard into the current file.

    VI starts out in command  mode. There are several commands that put the VI editor into   insemode. The most commonly used commands to get into insert mode are a and i. These twcommands are described below. Once you are in   insert  mode, you get out of it by hitting th

    escape key. If your terminal does not have an escape key, ^[ should work (control-[). You can hescape two times in a row and VI would definitely be in  command mode. Hitting escape while yoare already in command mode doesn't take the editor out of  command mode. It may beep to tell yothat you are already in that mode.

    2. How to Type Commands in Command Mode

    The command mode commands are normally in this format: (Optional arguments are given in th brackets)

    [count] command [where]

    Most commands are one character long, including those which use control characters. Thcommands described in this section are those which are used most commonly the VI editor.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    4/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    The count  is entered as a number beginning with any character from 1 to 9. For example, the

    command deletes a character under the cursor. If you type 23x while in command mode, it wdelete 23 characters. Some commands use an optional  where  parameter, where you can specihow many lines or how much of the document the command affects, the  where parameter can al

     be any command that moves the cursor.

    3. Word and Character Searching 

    The VI editor has two kinds of searches: string and character. For a string search, the / and commands are used. When you start these commands, the command just typed will be shown othe bottom line, where you type the particular string to look for. These two commands differ on

    in the direction where the search takes place. The / command searches forwards (downwards)

    the file, while the? command searches backwards (upwards) in the file. The n and N commanrepeat the previous search command in the same or opposite direction, respectively. Somcharacters have special meanings to VI, so they must be preceded by a backslash (\) to be includeas part of the search expression.

    Special characters:

    ^ Beginning of the line. (At the beginning of a search expression.). Matches a single character.* Matches zero or more of the previous character.$ End of the line (At the end of the search expression.)[ Starts a set of matching, or non-matching expressions.

    For example: /f[iae]t matches either of these: fit fat fet In this form, it matches anythingexcept these: /a[^bcd] will not match any of these, but anything with an a and another lette

    ab ac ad< Put in an expression escaped with the backslash to find the ending or beginning of a wordFor example: /\ should find only word the, but not words like these: there and other.

    > The character search searches within one line to find a character entered after the

    command. The f and F commands search for a character on the current line only. f search

    forwards and F searches backwards and the cursor moves to the position of the foundcharacter.

    The t and T commands search for a character on the current line only, but for  t, the cursor moves

    to the position before the character, and T searches the line backwards to the position after thecharacter.

    These two sets of commands can be repeated using the ; or  , command, where ; repeats the last

    character search command in the same direction, while , repeats the command in the reversedirection.

    4. Recovering Your Work When Something Goes Wrong with Your Terminal 

    The VI editor edits a temporary copy of your file, and after the editing is complete, or when yotell it to save, it puts the contents of the temporary copy into the original file. If something goewrong while you are editing your file, the VI editor will attempt to save whatever work you had

     progress, and store it for later recovery. (Note: If VI dies while you were working on any file,

    sends you an email message on how to recover it. The -r option stands for recovery. If you weediting the file vital info, and you accidentally got logged out, then the -r option of the 'vi' edit

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    5/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    should help. The command would look somewhat like this: vi -r vital info After using theoption once, though, you MUST save what you have recovered to the actual file... The -r optioonly works once per failed VI session.

    5. Basic Functions

    Key combination Function

    h or or Cursor left

    l or or Cursor right.

    k or  Cursor up.

    or  Cursor down.

    b Cursor left one word.w Cursor right one word.

    { Cursor up one paragraph.

    } Cursor down one paragraph.

    ^ Cursor to line starts.

    $ Cursor to line end.

     gg  Cursor to first line.

    G Cursor to last line.

    Get out of current mode.

    i Start insert mode.

    oInsert a blank line below the current line and then start insertmode.

    OInsert a blank line above the current line and then start insertmode.

    a Append (start insert mode after the current character).

     R Replace (start insert mode with overwrite).

    :wq Save (write) and quit.

    :q Quit.

    :q! Quit forced (without checking whether a save is required).

     x Delete (delete under cursor and copy to register).

     X  Backspace (delete left of cursor and copy to register).

    dd  Delete line (and copy to register).

    :j! Join line (remove newline at end of current line).

    u Undo.

    Ctrl-R Redo.

    de Delete to word end (and copy to register).

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    6/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    db Delete to word start (and copy to register).

    d$ Delete to line end (and copy to register).

    d ̂ Delete to line beginning (and copy to register).

    dd  Delete current line (and copy to register).

    2dd  Delete two lines (and copy to register).

    Paste clipboard (insert register).

    Ctrl-G Show cursor position.

    5G Cursor to line five.

    G Cursor to last line.

    / search-string  Search forwards for  search-string .

    ? search-string  Search backwards for  search-string .

    :-1,$s/ search-string  /replace-

     string  /gc Search and replace with confirmation starting at current line.

    :,$s/ search-string  /replace-

     string  /gc

    Search and replace with confirmation starting at line belowcursor.

    :,$s/\/replace-string  /gcSearch and replace whole words.

    :8,22s/ search-string  /replace-

     string  /gSearch and replace in lines 8 through 22 without confirmation.

    :%s/ search-string  /replace-

     string  /gSearch and replace whole file without confirmation.

    :w filename Save to file filename.

    :5,20w filenameSave lines 5 through 20 to file filename (use Ctrl-G to get linenumbers if needed).

    :5,$w! filename Force save lines 5 through to last line to file filename.

    :r filename Insert file filename.

    v Visual mode (start highlighting).

    Copy highlighted text to register.

    d  Delete highlighted text (and copy to register).

    Paste clipboard (insert register).Press v, then move cursor Search and replace within

    down a few lines, then, highlighted text.

    :helpReference manual (open new window with help screen inside--

     probably the most important command here!).

    :new Open new blank window.

    :split filename Open new window with filename.

    :q Close current window.

    :qa Close all windows.

    Ctrl-W j Move cursor to window below.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    7/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    Ctrl-W k  Move cursor to window above.

    Ctrl-W - Make window smaller.

    Ctrl-W + Make window larger.

    Introduction to Socket Programming

    6.1 Socket Creation

    A socket is an endpoint for communication. Two processes can communicate by creating sockeand sending messages between them. There are a variety of different types of sockets, differing the way the address space of the sockets is defined and the kind of communication that is allowe

     between sockets.

    A socket type is uniquely determined by a triple. In order for a remosocket to be reached, it must be possible to assign a name to it. The form that this name assumes determined by the communication domain or  address family to which the socket belongs. There also an   abstract type or   style of communication associated with each socket. This gives thsemantics of communication for that socket. Finally, there is a specific protocol that is used withe socket.

    A socket can be created with the socket()system call by specifying the desired address familsocket type, and protocol.

    socket_descriptor = socket (domain, type, protocol)

    int socket_descriptor, domain, type, protocol;

    This call returns a small positive integer called a  socket descriptor that can be used as a parametto reference the socket in subsequent system calls. Socket descriptors are similar to file descripto

    returned by the open() system call. Each open() or  socket() call will return the smalleunused integer. Thus a given number denotes either an open file, a socket, or neither (but nev

     both). Socket and file descriptors may be used interchangeably in many system calls. For exampl

    the close() system call is used to destroy sockets.

    6.2 Domains

    The communication domain or address family to which a socket belongs specifies a certain addreformat. All later operations on a socket will interpret the supplied address according to thspecified format. The various address formats are defined as manifest constants in the fi

    . Examples are AF_UNIX (UNIX path names), AF_INET (DARPA Internaddresses), and AF_OSI (as specified by the international standards for Open SystemInterconnection). AF_UNIX and AF_INET are the most important address families. The gener

    form of an address is represented by the sockaddr structure defined in .

    struct sockaddr { short sa_family; /* address family */ 

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    8/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    char sa_data[14]; /* up to 14 bytes of direct address */  }

    Note: You must include  before .

    When a socket is created, it does not initially have an address associated with it. However, sinceis impossible for a remote host or process to find a socket unless it has an address, it is important

     bind an address to the socket. A socket does not have a name until an address is explicitly assigne

    to it with the bind() system call.

    status = bind(sock, address, addrlen)

    int status; /* status returns 0 for success, -1 otherwise */ int sock; /* descriptor returned by socket() */ 

    struct sockaddr *address;int addrlen; /* size of address (in bytes) */ 

    This call fails if the address is already in use, the address is not in the correct format for the addrefamily specified, or the socket already has an address bound to it.

    6.2.1 UNIX domain

    In the UNIX domain, a socket is addressed by a UNIX path name that may be up to 108 charactelong. The binding of a path name to a socket results in the allocation of an inode and an entry the path name into the file system. This necessitates removing the path name from the file system

    (using unlink() system call) when the socket is closed. The created file is only used to providename for the socket and does not play a role in the actual transfer of data. When using sockets

    the UNIX domain, it is advisable to only use path names for directories (/tmp) directly mounted o

    the local disk. The UNIX domain only allows interprocess communication for processes workinon the same machine. The structure sockaddr_un used to define the UNIX address format can b

    found in .struct sockaddr_un { 

    short sun_family; /* AF_UNIX */ 

    char sun_path[108-4]; /* path name */  }

    Note:When specifying the length of UNIX domain addresses for system calls, use sizeof(struc

    sockaddr_un). Using the size of  sockaddr will cause the call to fail.

    6.2.2 Internet domainIn the DARPA Internet domain, addresses consist of two parts. First part is a host addre(consisting of a network number and a host number) and the later is a port number (also known a transport suffix). This host address allows processes on different machines to communicate. Th

     port number is like a mail box that allows multiple addresses on the same host. The structu

    sockaddr_in describing an address in the Internet domain is defined in the file .struct sockaddr_in { 

    short sin_family; /* AF_INET */ u_short sin_port; /* port number */ 

    struct in_addr sin_addr; /* see struct below */ char sin_zero[8]; /* not used */ 

     }

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    9/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    struct in_addr { union { 

    struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;struct { u_short s_w1,s_w2; } S_un_w;

    u_long S_addr;

     } S_un;#define s_addr S_un.S_addr /* can be used for most tcp& ip code */

     }

    It is often useful to bind a specific service to a "well-known" port, enabling remote processes locate the required server easily. Examples of well-known ports are 79 for the "finger" service an513 for remote login. The kernel reserves the first 1024 port numbers for its own use. There is

    network services database in /etc/services that can be queried by using the system cal

    getservbyname() and getservbyport().Each of these routines returns a pointer to the structu

    servent defined in . If the port field in the address parameter to bind is specified as zerthe system will assign an unused port number. The assigned port number can be discovered b

    calling getsockname(). In the Internet domain, UDP and TCP can use the same port numberThere is no confusion in naming because ports bound to sockets with different protocols canncommunicate. Ports numbered less than 1024 are "reserved"--only processes running as superusmay bind to them.

    Internet host addresses are specified in four bytes (32 bits). They are typically represented by standard `.' notation, a.b.c.d. The bytes of the address are represented by decimal integerseparated by periods, and ordered from high order to low order. This ordering is called netwoorder and is the order in which addresses are transmitted over the network. For example, thInternet address for the host garfield.cs.wisc.edu is 128.105.1.3 which corresponds to the unsigneinteger 80690103 in hex, or 2154365187 in decimal. Some hosts (such as the VAX), howevehave a host order for these integer values that reverses the order of the bytes. When a word transmitted from such a host (or when a C program treats a word as a sequence of bytes), the loworder byte is transmitted first (has the lowest address). Thus, it is necessary to reverse the bytes o

    an address, stored in an integer, before transmitting it. The system routines htonl() and ntohlare provided to convert long (32-bit) integers from host to network order and vice versa. Similarl

    htos() and ntohs() swap the bytes of short (16-bit) integers, such as port numbers. System cal

    that return or demand Internet addresses and port numbers (such as gethostbyname() or  bind(which is described above), deal entirely in network order, so you normally don't have to worrabout all this. However, if you want to print out one of these values or read it in, you will have convert from/to host order.

    An Internet host address can be decomposed into two parts, a network number and a local addresThere are three formats for Internet addresses (see inet(3N)), each of which partitions the 32 bidifferently. "Class A" addresses have a one-byte network number (the high order byte), and a

     byte host number. "Class B" addresses have two bytes each of network and host number, and "claC" networks have three bytes of network number and one byte of host number. (Thus a class network can have at most 256 hosts). The high-order bits of an address determine its clasAddresses starting with a zero are class A addresses, addresses starting with 10 are class B, anaddresses starting with 110 are class C. Thus there can be at most 128 class A networks and most 214 = 16,384 class B networks.

    The system calls gethostbyaddr() and gethostbyname() can be used to look up the host addre(see gethostent(3N) and host(5)). Each of these calls returns a pointer to the structure hoste

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    10/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    defined in . Host addresses are returned in network order, the proper format for a call

    bind(). The system routine memcpy() can be used to copy the host address into the sockaddr_

    structure. If a zero host address is given (the wildcard value INADDR_ANY can be used) in the call

    bind(), the local host address will be automatically supplied. Another reason for usin

    INADDR_ANY is that a host may have multiple Internet addresses; addresses specified this way w

    match any incoming messages with a valid Internet address.

    7. Styles of Communication

    The type field of the socket() call specifies the abstract "style of communication" to be used wi

    that socket. These types are defined as manifest constants in . The followin

    types are currently defined: SOCK_STREAM (stream), SOCK_DGRAM (datagram), SOCK_RAW (ra

     protocol interface), SOCK_RDM (reliable datagrams), and SOCK_SEQPACKET (sequenced packstream). Each of these abstractions is supported by different protocols. We will be primariconcerned with the SOCK_STREAM and SOCK_DGRAM abstractions.

    7.1 Datagram Sockets

    The SOCK_DGRAM type provides a datagram model of communication. A datagram service connectionless and unreliable. Independent (and usually small) messages called  datagrams aaccepted by the transport protocol and sent to the address specified. These messages may be losduplicated, or received out of order. An important characteristic of datagrams is that messag

     boundaries are maintained. This means that individual datagrams (i.e., messages sent with separa

    calls) will be kept separate when they are received at the other end. A revcfrom() call on

    datagram socket will only return the next datagram available. The SOCK_DGRAM type can be usedthe UNIX or Internet domain. When used in the Internet domain, it is supported by the Interntransport protocol UDP. The call

    sock = socket(AF_INET, SOCK_DGRAM, 0)returns a UDP datagram socket.

    7.2 Stream Sockets

    The STREAM_SOCK type provides a stream model of communication. This service is reliable anconnection-oriented. Data is transmitted on a full-duplex, flow-controlled byte stream. Thtransport protocol supporting this socket type must ensure that data is delivered in order withouloss, error, or duplication. Otherwise, it must abort the connection and report an error to the useMessage boundaries are not  preserved on a stream socket. Before data can be sent or received on

    stream socket, the socket must be made the active or passive end of a connection using the systecalls listen(), accept(), and connect() discussed in Section 2. Again, the SOCK_STREAabstraction can be used in both the UNIX and Internet domains. In the Internet domain, it supported by the Internet transport protocol TCP. The call

    sock = socket(AF_INET, SOCK_STREAM, 0)returns a TCP stream socket.

    8. Protocols

    A protocol is a set of communication conventions for regulating the exchange of informatio between two parties. Transport protocols that support the styles of communication described abovare implemented as code in the UNIX kernel. These concrete protocols actually realize thsemantics defined by the socket type. User Datagram Protocol (UDP), Transmission Contr

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    11/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    Protocol (TCP), and Internet Protocol (IP) all belong to the Internet family of protocols. Eacmember of this protocol family supports a different abstract type. UDP supports datagram socket

    TCP supports stream sockets, and the SOCK_RAW type of socket provides a raw interface to IP. T

    the ISO connection-based transport protocol, conceptually supports the   SOCK_SEQPACKEabstraction, although it is not currently implemented in Berkeley Unix. There is currently only on

     protocol supporting a given socket abstraction in a particular domain. Nothing, however, prevenfuture protocols from being implemented that support the same abstract type in the same domain aan existing protocol. The protocol to be used is specified in the protocol field of the socket caThere are three ways to specify the protocol. First, if a zero is supplied, the system provides thdefault protocol for that address family and socket type; this is the most common method. Secon

    manifest constants describing protocols, such as IPPROTO_UDP, can be found in 

  • 8/9/2019 Network Lab Manual 2

    12/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    A socket becomes the passive end of a connection by first doing a listen() and then a

    accept().

    status = listen(sock, queuelen)

    int sock, queuelen;

    Listen initializes a queue for waiting connection requests. The parameter  queuelen specifies thmaximum number of queued connections that will be allowed. The maximum queue length

    currently limited by the system to 5. The manifest constant SOMAXCONN from 

  • 8/9/2019 Network Lab Manual 2

    13/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    manner and in the case of Windows, the crash will most likely take OS for the ride, too. There arways to avoid that. Always convert data received from the network into the native byte order!

    @E$DSDSAFSADIJF*HER(e0rueqireir90r7937ufkjdkf’sd-0ds9r037298y32jefke)

    10.4 Data TransferThe system call pairs (read(), write()), (recv(), send()), (recvfrom(), sendto()

    (recvmsg(), sendmsg()), and (readv(), writev()) can all be used to transfer data on socket

    The most appropriate call depends on the exact functionality required. send() and recv() atypically used with connected stream sockets. They can also be used with datagram sockets if th

    sender has previously done a connect() or the receiver does not care who the sender is. sendto

    and recvfrom() are used with datagram sockets. sendto() allows one to specify the destinatio

    of the datagram, while revcfrom() returns the name of the remote socket sending the messag

    read() and write() can be used with any connected socket. These two calls may be chosen fefficiency considerations. The remaining data transfer calls can be used for more specialize

     purposes. writev() and readv() make it possible to scatter and gather data to/from separa

     buffers. sendmsg() and recvmsg() allow scatter/gather capability as well as the ability

    exchange access rights. The calls read(), write(), readv(), and writev() take either a sockdescriptor or a file descriptor as their first argument; all the rest of the calls require a sockdescriptor.

    count = send(sock, buf, buflen, flags)

    int count, sock, buflen, flags; char *buf;

    count = recv(sock, buf, buflen, flags)int count, sock, buflen, flags; char *buf;

    count = sendto(sock, buf, buflen, flags, to, tolen)int count, sock, buflen, flags, tolen;char *buf;

    struct sockaddr *to;

    count = recvfrom(sock, buf, buflen, flags, from, fromlen)

    int count, sock, buflen, flags, *fromlen;char *buf;

    struct sockaddr *from;

    For the send calls, count returns the number of bytes accepted by the transport layer, or -1 if som

    error is detected locally. A positive return count is no indication of the success of the data transferNote: If made non blocking, send may accept some but not all of the bytes in the data buffer.Threturn value should be checked so that the remaining bytes can be sent if necessary. For receivcalls, count returns the number of bytes actually received, or -1 if some error is detected.

    The first parameter for each call is a valid socket descriptor. The parameter  buf  is a pointer to th

    caller's data buffer. In the send() calls, buflen is the number of bytes being sent; in the receivecalls, it indicates the size of the data area and the maximum number of bytes the caller is willing

    receive. The parameter  to in the sendto() call specifies the destination address (conforming to

     particular address family) and tolen specifies its length. The parameter  from in the recvfrom() caspecifies the source address of the message. fromlen is a value/result parameter that initially giv

    the size of the structure pointed to by from and then is modified on return to indicate the actulength of the address.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    14/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    The flags parameter, which is usually given zero as an argument, allows several special operationon stream sockets. It is possible to send out-of-band data or "peek" at the incoming messag

    without actually reading it. The flags MSG_OOB and MSG_PEEK are defined in 

  • 8/9/2019 Network Lab Manual 2

    15/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    13. DNS resolver

    DNS stands for "Domain Name Service". In a nutshell, you tell it what the human-readable addreis for a site, and it'll give you the IP address (so you can use it with bind(), connect(), sendto(), owhatever you need it for.)Use the function gethostbyname():

    struct hostent *gethostbyname(const char *name);It returns a pointer to a struct hostent

    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] And here are the descriptions of the fields in the struct hostent:h_name -- Official name of the host.h_aliases -- A NULL-terminated array of alternate names for the host.h_addrtype -- The type of address being returned; usually AF_INET .h_length -- The length of the address in bytes.h_addr_list  -- A zero-terminated array of network addresses for the host. Host addresses are

     Network Byte Order.h_addr -- The first address in h_addr_list .gethostbyname() returns a pointer to the filled struct hostent, or NULL on error. (But  errno is nset--h_errno is set instead. See herror(), below.)

    14. Client-Server architecture

     Normally network deals with client processes talking to server processes and vice-versa. Taketelnet, for instance. When you connect to a remote host on port 23 with telnet (the client), a

     program on that host (called telnetd, the server) springs to life. It handles the incoming telnetconnection, sets you up with a login prompt, etc.

    Client-Server Interaction.

    The exchange of information between client and server is summarized Note that the client-server pair can speak SOCK_STREAM, SOCK_DGRAM, or anything else (along as they're speaking the same thing.) Some good examples of client-server pairs are

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    16/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    telnet/telnetd, ftp/ftpd, or bootp/bootpd. Every time you use ftp, there's a remote program, ftpdthat serves you.Often, there will only be one server on a machine, and that server will handle multiple clients usinfork(). The basic routine is: server will wait for a connection, accept() it, and fork() a child procesto handle it.

    14.1 Understanding Clients and ServersThe Clients are known as Active and Server is known as Passive, or Outgoing andIncomming.There is no defacto standard to be sure for describing the two parts... but Client Serveis used allot.

    Client = Active = OutgoingServer = Passive = IncommingHeres is a basic run down on the application level and network level, of the different socketconnections.

    14.2 Client Communications

     Application level Network PC level 

    socket( ); socket is called by the program. This will set up a datastructure for the operating system to use, to read and write,and control the socket.

    *bind( ); With active ( client ) sockets you do not always need to call bind, but if you would like to designate a particular IP port to be used with the UDP socket you will need to fill in the structsockaddr_in, and make a call to bind();, bind is used to set

    the address and port number associated with a given socketconnect( ); With UDP sockets you do not always need to call connect before sending, With TCP this connect call will make the OS preform what is known as "the TCP three parthandshake". This consists of the Client computer ( thecomputer that called connect ) sending a SYN packet, to theServer computer. If all goes well the server computer willrespond with an SYN,ACK packet, and then finally the Clientcomputer sends a final ACK packet. If all this works wellconnect( ) returns a posetive integer, and you will have aconnected socket .

    send( );, andor recv( );, sendto( );,recvfrom( );

    UDP can use send( ), recv( ), sendto( ), recvfrom( ), read( ),and write( ) for passing data. If you have used bind to bind aipaddress and port, you will most likely want to just use recvfor reading, and send for sending. If you have not used bindon the UDP socket it may be nessary to use sendto, and recv,or recvfrom. When using TCP it is more common for applications to use send, and recv, allthough sendto, recvfrom,and read and write do work.

    close( );, shutdown( ); These functions will close the socket and deallocate anyresources from the OS.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    17/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    14.3 Server Communications

     Application level Network PC level 

    socket( );is called by the program

    This will set up a data structure for theoperating system to use, to read and write,

    and control the socket*bind( ); Bind is used to realte a local port number to

    a socket, therefore if you wanted to create aserver that ran on a specific port, such astelnet, FTP, and HTTP, you will need touse bind in your sever application.

    *listen( ); The call to listen( ) is only needed in TCPapplications, this will allow you to specifyhow many clients can connect to any givenTCP port at one time.

    *accept( ); The call to accept( ) again , is only neededin TCP applications, this will allow you to preform the server side of the three wayhandshake when a client connects. If accept is successfull it will return a newsocket to you for reading and writting.

    send( );, andor recv( );, sendto( );, recvfrom( );

    UDP can use send( ), recv( ), sendto( ),recvfrom( ), read( ), and write( ) for passingdata. If you have used bind to bind aipaddress and port, you will most likelywant to just use recv for reading, and send

    for sending. If you have not used bind onthe UDP socket it may be nessary to usesendto, and recv, or recvfrom.

    close( );, shutdown( ); These functions will close the socket anddeallocate any resources from the OS.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    18/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    Introduction to NS-2 Simulator

     NS is a discrete event simulator for networking research. It provides substantial support fsimulation of TCP, routing, and multicast protocols over wired and wireless (local and satellit

    networks.

    15.1 Downloading/Installing ns

     NS should configure and build on Unix systems. To install NS-2 in your own system, you cadownload the package from http://www.isi.edu/nsnam/ns/ns-build.html (To install NS in windowsystems, please also refer this page). There are two ways to build ns: from the various packages o‘all-in-one’ package. For simplicity, it is recommended to start with the ‘all-in-one’ package.Build NS:

    Entering NS2 directory and execute:./gunzip ns-allinone-***.tar.gz /* *** is the version number */

    /* unzip the file */

    ./tar xvf ns-allinone-***.tar /* untar the file */

    ./install

    ./validatePlease refer http://www.isi.edu/nsnam/ns/ns-problems.html for any installation problems.

    15.2 Starting ns

    You start ns with the command 'ns ' (assuming that you are in the directory with the nexecutable, or that your path points to that directory), where '' is the name of a Tcl scrifile which defines the simulation scenario (i.e. the topology and the events). You could also justart ns without any arguments and enter the Tcl commands in the Tcl shell, but that is definiteless comfortable. For information on how to write your own Tcl scripts for ns.Everything el

    depends on the Tcl script. The script might create some output on stdout, it might write a trace fior it might start nam to visualize the simulation. Or all of the above. These possibilities will all bdiscussed in later sections.

    15.3 Starting namYou can either start nam with the command 'nam ' where '' is the name ofnam trace file that was generated by ns, or you can execute it directly out of the Tcl simulatioscript for the simulation which you want to visualize. Below you can see a screenshot of a namwindow where the most important functions are being explained.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    19/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    15.4 How to start

     Now we are going to write a 'template' that you can use for all of the first Tcl scripts. You can

    write your Tcl scripts in any text editor like joe or emacs. I suggest that you call this first example'example1.tcl'.

    First of all, you need to create a simulator object. This is done with the command

    set ns [new Simulator] 

     Now we open a file for writing that is going to be used for the nam trace data.

    set nf [open out.nam w] $ns namtrace-all $nf 

    The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the second lin

    we tell the simulator object that we created above to write all simulation data that is going to brelevant for nam into this file.The next step is to add a 'finish' procedure that closes the trace filand starts nam.

     proc finish {} {  global ns nf 

    $ns flush-traceclose $nf 

    exec nam out.nam &exit 0

     }

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    20/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    You don't really have to understand all of the above code yet. It will get clearer to you once yosee what the code does. The next line tells the simulator object to execute the 'finish' procedurafter 5.0 seconds of simulation time.

    $ns at 5.0 "finish"

    You probably understand what this line does just by looking at it. ns provides you with a versimple way to schedule events with the 'at' command. The last line finally starts the simulation.

    $ns run

    You can actually save the file now and try to run it with 'ns example1.tcl'. You are going to get aerror message like 'nam: empty trace file out.nam' though, because until now we haven't defineany objects (nodes, links, etc.) or events. You will have to use the code from this section as startin

     point in the other sections. #Create a simulator objectset ns [new Simulator]

    #Open the nam trace fileset nf [open out.nam w]

    $ns namtrace-all $nf 

    #Define a 'finish' procedure proc finish {} {

    global ns nf $ns flush-trace

    #Close the trace fileclose $nf 

    #Execute nam on the trace fileexec nam out.nam &exit 0

    }

    # Insert your own code for topology creation# and agent definitions, etc. here

    #Call the finish procedure after 5 seconds simulation time$ns at 5.0 "finish"

    #Run the simulation$ns run

    15.5 Two nodes, one link In this section we are going to define a very simple topology with two nodes that are connected ba link. The following two lines define the two nodes. (Note: You have to insert the code in th

    section before the line '$ns run', or even better, before the line '$ns at 5.0 "finish"').set n0 [$ns node] set n1 [$ns node] A new node object is created with the command '$ns node'. The above code creates two nodes anassigns them to the handles 'n0' and 'n1'. The next line connects the two nodes.

    $ns duplex-link $n0 $n1 1Mb 10ms DropTail 

    This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with the bandwidth 1Megabit, a delay of 10ms and a DropTail queue.

     Now you can save your file and start the script with 'ns example1.tcl'. nam will be startedautomatically and you should see an output that resembles the picture below.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    21/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    #Create a simulator objectset ns [new Simulator]

    #Open the nam trace fileset nf [open out.nam w]$ns namtrace-all $nf 

    #Define a 'finish' procedure proc finish {} {

    global ns nf $ns flush-trace

    #Close the trace fileclose $nf 

    #Execute nam on the trace fileexec nam out.nam &exit 0

    }

    #Create two nodesset n0 [$ns node]set n1 [$ns node]

    #Create a duplex link between the nodes$ns duplex-link $n0 $n1 1Mb 10ms DropTail

    #Call the finish procedure after 5 seconds of simulation time$ns at 5.0 "finish"

    #Run the simulation$ns run

    15.5.1 Sending data

    The next step is to send some data from node n0 to node n1. In ns, data is always being sent fromone 'agent' to another. So the next step is to create an agent object that sends data from node n

    and another agent object that receives the data on node n1.

    #Create a UDP agent and attach it to node n0set udp0 [new Agent/UDP] 

    $ns attach-agent $n0 $udp0

    # Create a CBR traffic source and attach it to udp0set cbr0 [new Application/Traffic/CBR] 

    $cbr0 set packetSize_ 500$cbr0 set interval_ 0.005

    $cbr0 attach-agent $udp0

    These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic generatorthe UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-explaining. Th

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    22/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

     packet Size is being set to 500 bytes and a packet will be sent every 0.005 seconds (i.e. 200 packe per second). The next lines create a Null agent which acts as traffic sink and attach it to node n1.

    set null0 [new Agent/Null] $ns attach-agent $n1 $null0

     Now the two agents have to be connected with each other.

    $ns connect $udp0 $null0And now we have to tell the CBR agent when to send data and when to stop sending. Note: It

     probably best to put the following lines just before the line '$ns at 5.0 "finish"'.

    $ns at 0.5 "$cbr0 start"

    $ns at 4.5 "$cbr0 stop"This code should be self-explaining again. Now you can save the file and start the simulationagain. When you click on the 'play' button in the nam window, you will see that after 0.5simulation seconds, node 0 starts sending data packets to node 1. You might want to slow namdown then with the 'Step' slider.

     Now you start some experiments with nam and the Tcl script. You can click on any packet in the

    nam window to monitor it, and you can also click directly on the link to get some graphs withstatistics.Try to change the 'packetsize_' and 'interval_' parameters in the Tcl script to see whathappens.#Create a simulator objectset ns [new Simulator]

    #Open the nam trace fileset nf [open out.nam w]$ns namtrace-all $nf 

    #Define a 'finish' procedure proc finish {} {

    global ns nf 

    $ns flush-trace#Close the trace file

    close $nf #Execute nam on the trace file

    exec nam out.nam &exit 0

    }

    #Create two nodesset n0 [$ns node]set n1 [$ns node]

    #Create a duplex link between the nodes

    $ns duplex-link $n0 $n1 1Mb 10ms DropTail

    #Create a UDP agent and attach it to node n0

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    23/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    set udp0 [new Agent/UDP]$ns attach-agent $n0 $udp0

    # Create a CBR traffic source and attach it to udp0set cbr0 [new Application/Traffic/CBR]$cbr0 set packetSize_ 500

    $cbr0 set interval_ 0.005 $cbr0 attach-agent $udp0

    #Create a Null agent (a traffic sink) and attach it to node n1set null0 [new Agent/Null]$ns attach-agent $n1 $null0

    #Connect the traffic source with the traffic sink $ns connect $udp0 $null0

    #Schedule events for the CBR agent$ns at 0.5 "$cbr0 start"$ns at 4.5 "$cbr0 stop"

    #Call the finish procedure after 5 seconds of simulation time$ns at 5.0 "finish"

    #Run the simulation$ns run

    15.6 The topology

    You will always have to create a simulator object, you will always have to start the simulation withe same command, and if you want to run nam automatically, you will always have to open a tracfile, initialize it, and define a procedure which closes it and starts nam.

     Now insert the following lines into the code to create four nodes.

    set n0 [$ns node] 

    set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] The following piece of Tcl code creates three duplex links between the nodes.$ns duplex-link $n0 $n2 1Mb 10ms DropTail 

    $ns duplex-link $n1 $n2 1Mb 10ms DropTail 

    $ns duplex-link $n3 $n2 1Mb 10ms DropTail You can save and start the script now. You might notice that the topology looks a bit awkward inam. You can hit the 're-layout' button to make it look better, but it would be nice to have sommore control over the layout. Add the next three lines to your Tcl script and start it again.

    $ns duplex-link-op $n0 $n2 orient right-down

    $ns duplex-link-op $n1 $n2 orient right-up$ns duplex-link-op $n2 $n3 orient right You will probably understand what this code does when you look at the topology in the namwindow now. It should look like the picture below.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    24/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    15.7 The events Now we create two UDP agents with CBR traffic sources and attach them to the nodes n0 and n1.Then we create a Null agent and attach it to node n3.

    #Create a UDP agent and attach it to node n0set udp0 [new Agent/UDP] 

    $ns attach-agent $n0 $udp0

    # Create a CBR traffic source and attach it to udp0set cbr0 [new Application/Traffic/CBR] 

    $cbr0 set packetSize_ 500$cbr0 set interval_ 0.005

    $cbr0 attach-agent $udp0

    #Create a UDP agent and attach it to node n1

    set udp1 [new Agent/UDP] $ns attach-agent $n1 $udp1

    # Create a CBR traffic source and attach it to udp1

    set cbr1 [new Application/Traffic/CBR] $cbr1 set packetSize_ 500

    $cbr1 set interval_ 0.005$cbr1 attach-agent $udp1

    set null0 [new Agent/Null] 

    $ns attach-agent $n3 $null0The two CBR agents have to be connected to the Null agent.

    $ns connect $udp0 $null0$ns connect $udp1 $null0We want the first CBR agent to start sending at 0.5 seconds and to stop at 4.5 seconds while thsecond CBR agent starts at 1.0 seconds and stops at 4.0 seconds.$ns at 0.5 "$cbr0 start"

    $ns at 1.0 "$cbr1 start"$ns at 4.0 "$cbr1 stop"

    $ns at 4.5 "$cbr0 stop"When you start the script now with 'ns example2.tcl', you will notice that there is more traffic othe links from n0 to n2 and n1 to n2 than the link from n2 to n3 can carry. A simple calculatioconfirms this: We are sending 200 packets per second on each of the first two links and the packe

    size is 500 bytes. This results in a bandwidth of 0.8 megabits per second for the links from n0 to nand from n1 to n2. That's a total bandwidth of 1.6Mb/s, but the link between n2 and n3 only hascapacity of 1Mb/s so obviously some packets are being discarded But which ones? Both flows ar

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    25/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

     black, so the only way to find out what is happening to the packets is to monitor them in nam bclicking on them. In the next two sections I'm going to show you how to distinguish betweedifferent flows and how to see what is actually going on in the queue at the link from n2 to n3.

    Marking flowsAdd the following two lines to your CBR agent definitions.

    $udp0 set class_ 1

    $udp1 set class_ 2

    The parameter 'fid_' stands for 'flow id'.

     Now add the following piece of code to your Tcl script, preferably at the beginning after thesimulator object has been created, since this is a part of the simulator setup.

    $ns color 1 Blue$ns color 2 Red

    This code allows you to set different colors for each flow id.

     Now you can start the script again and one flow should be blue, while the other one is red. Watcthe link from node n2 to n3 for a while, and you will notice that after some time the distributio

     between blue and red packets isn't too fair anymore (at least that's the way it is on my system). the next section I'll show you how you can look inside this link's queue to find out what is going o

    there.

    Monitoring a queueYou only have to add the following line to your code to monitor the queue for the link from n2 ton3.

    $ns duplex-link-op $n2 $n3 queuePos 0.5

    Start ns again and you will see a picture similar to the one below after a few moments.

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    26/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    You can see the packets in the queue now, and after a while you can even see how the packets a being dropped, though (at least on my system, I guess it might be different in later or earlireleases) only blue packets are being dropped. But you can't really expect too much 'fairness' froma simple Drop Tail queue. So let's try to improve the queuing by using a SFQ (stochastic fa

    queuing) queue for the link from n2 to n3. Change the link definition for the link between n2 ann3 to the following line.$ns duplex-link $n3 $n2 1Mb 10ms SFQ

    The queuing should be 'fair' now. The same amount of blue and red packets should be dropped.Appendix A

    Header Files

    When programming sockets you will need to #include the following header files:

    #include /* basic system data types */ #include /* basic socket definitions */ 

    #include /* timeval{} for select() */ #include /* timespec{} for pselect() */  

    #include /* sockaddr_in{} and other Internet defns */ 

    #include /* inet(3) functions */ #include

    #include /* for nonblocking, on windows don't use fnctl(), use ioctlsocket()*/ 

    #include #include

    #include #include

    #include #include /* for S_xxx file mode constants */ 

    #include /* this file is typically only for Linux *nix OS's */ 

    #include #include /* for Unix domain sockets */ 

    #include /* for sdprintf */  Usefull Defines

     /* Define bzero( ) as a macro if it's not in standard C library. */ 

    #ifndef HAVE_BZERO#define bzero( ptr, n ) memset( ptr, 0, n )

    #endif 

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    27/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

     /* Following shortens all the type casts of pointer arguments */ 

    #define SA struct sockaddr #define SA_in struct sockaddr_in

    #define min( a , b ) ( ( a ) < ( b ) ? ( a ) : ( b ) )#define max( a , b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )

    Appendix B

    Program to create a socket

    /* Ex-1 Program To Create a Socket */#include /* NEEDED HEADER FILES */

    #include #include #include #include#includeint main(){int sockfd1,sockfd2; /* sokcet file descriptors */sockfd1=socket(AF_INET,SOCK_STREAM,0); /* socket system call */sockfd2=socket(PF_INET,SOCK_DGRAM,0);if(sockfd1==-1) /* error checking */{

     printf("Socket1 not Created\n");}else{

     printf("Socket1 Created and \t Socket1 File Descriptor value is %d \n",sockfd1);

    if(sockfd2==-1){

     printf("socket2 creation error");}else

    { printf("Socket2 created and \t socket2 descriptor value is %d\n",sockfd2);}

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    28/52

       h  t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS230

    }}

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    29/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to Bind a socket/* Ex-2 Program to Bind a Socket */#include

    #include#include#include#define PORTNO 2000 /* Type definition of a Port number */int main(){

    int sockfd,i=PORTNO;struct sockaddr_in myaddr; /* Builtin structure for internet address */if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){printf("Socket Creation Error\n");}

    myaddr.sin_family=AF_INET; /* Structure variable definition */myaddr.sin_port=htons(PORTNO);myaddr.sin_addr.s_addr=INADDR_ANY;

    memset(&(myaddr.sin_zero),'\0',8); /* fills with constant byte to remaining space */

    /* socket Binding process and error checking */if(bind(sockfd,(struct sockaddr *)&myaddr,sizeof(struct sockaddr))!=-1)

    { printf(" Socket is Binded at port %d\n",i);

    }else{ printf("Binding Error\n");}}

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    30/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to implement listen() system call

    /* Ex-3 Program to implement LISTEN system call */

    #include /* These are the usual header files */#include #include #include

    #define PORT 3550 /*Assigning Port number */#define BACKLOG 12 /* Number of allowed connections */

    main(){

    int fd; /* file descriptors */

    struct sockaddr_in server; /* server's address information */struct sockaddr_in client; /* client's address information */

    int sin_size;int x;if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ){ /* calls socket() */ printf("socket() error\n");exit(-1);

    }server.sin_family = AF_INET;server.sin_port = htons(PORT); /* Remember htons() from "Conversions" section? =) */server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically * bzero(&(server.sin_zero),8); /* zero the rest of the structure */

    if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1) /* calls bind() */{ printf("bind() error\n");

    exit(-1);}

    x=listen(fd,BACKLOG) ; /* calls listen() */if(x==-1){

     printf("listen() error\n");exit(-1);

    }else{

     printf(Server is in listening mode \n );

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    31/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    }close(fd); /* close fd */

    }

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    32/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program for accept() system call

    /* Ex-3 Program to implement ACCEPT system calls */

    #include /* These are the usual header files */#include #include #include

    #define PORT 3550 /* Assigning Port numbers */#define BACKLOG 2 /* Number of allowed connections */

    main(){

    int fd, fd2; /* file descriptors */

    struct sockaddr_in server; /* server's address information */struct sockaddr_in client; /* client's address information */

    int sin_size;if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* calls socket() */{ printf("socket() error\n");exit(-1);

    }

    server.sin_family = AF_INET;server.sin_port = htons(PORT); /* Remember htons() from "Conversions" section */server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically * bzero(&(server.sin_zero),8); /* zero the rest of the structure */

    if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ /* calls bind() */ printf("bind() error\n");exit(-1);

    }

    if(listen(fd,BACKLOG) == -1) /* calls listen() */{

     printf("listen() error\n");exit(-1);

    } printf("server is in accept mode \n ");

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    33/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    while(1){

    sin_size=sizeof(struct sockaddr_in);if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1){ /* calls accept() */ printf("accept() error\n");

    exit(-1);}else printf(" Server is in accept mode "); printf("You got a connection from %s\n",inet_ntoa(client.sin_addr) ); /* prints client's IP */

    close(fd2); /* close fd2 */}}

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    34/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to implement Client/Server architecture using TCP

    /* Ex-4 Program to implement client/server architecture using TCP/IP */

    #include /* These are the usual header files */#include #include #include

    #define PORT 3550 /* Assigning Port number */#define BACKLOG 2 /* Number of allowed connections */

    main(){int fd, fd2; /* file descriptors */

    struct sockaddr_in server; /* server's address information */struct sockaddr_in client; /* client's address information */

    int sin_size;

    if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* calls socket() */{ printf("socket() error\n");exit(-1);

    }

    server.sin_family = AF_INET;server.sin_port = htons(PORT); /* Remember htons() from "Conversions" section*/server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically */ bzero(&(server.sin_zero),8); /* zero the rest of the structure */

    if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1) /* calls bind() */{

     printf("bind() error\n");exit(-1);

    }

    if(listen(fd,BACKLOG) == -1) /* calls listen() */{

     printf("listen() error\n");exit(-1);

    }

    while(1){

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    35/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    sin_size=sizeof(struct sockaddr_in);if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1) /* calls accept() */{ printf("accept() error\n");exit(-1);

    }

     printf("You got a connection from %s\n",inet_ntoa(client.sin_addr) ); /* prints client's IP */

    send(fd2,"Welcome to my server.\n",22,0); /* send to the client welcome message */

    close(fd2); /* close fd2 */}

    }

    /*End of TCP server program */

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    36/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to implement TCP client

    #include #include

    #include #include #include /* netdb.h is needed for struct hostent */

    #define PORT 3550 /* Open Port on Remote Host */#define MAXDATASIZE 100 /* Max number of bytes of data */

    int main(int argc, char *argv[]){int fd, numbytes; /* files descriptors */char buf[MAXDATASIZE]; /* buf will store received text */

    struct hostent *he; /* structure that will get information about remote host */struct sockaddr_in server; /* server's address information */

    if (argc !=2) { /* this is used because our program will need oneargument (IP) */

     printf("Usage: %s \n",argv[0]);exit(-1);

    }if ((he=gethostbyname(argv[1]))==NULL){ /* calls gethostbyname() */ printf("gethostbyname() error\n");exit(-1);

    }if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){ /* calls socket() */ printf("socket() error\n");exit(-1);

    }server.sin_family = AF_INET;server.sin_port = htons(PORT); /* htons() is needed again */server.sin_addr = *((struct in_addr *)he->h_addr); /*he->h_addr passes "*he"'s info to

    "h_addr" */ bzero(&(server.sin_zero),8);if(connect(fd, (struct sockaddr *)&server,sizeof(struct sockaddr))==-1)

    { printf("connect() error\n");exit(-1);

    }if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1) /* calls recv() */

    { printf("recv() error\n");exit(-1);

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    37/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    } buf[numbytes]='\0'; printf("Server Message: %s\n",buf); /* it prints server's welcome message =) */close(fd); /* close fd =) */

    }

    /* End of the tcp client program */

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    38/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to get the Host name

    /* Program to get the hostname */

    #include /* These are the usual header files */#include#include#include#include#include

    int main(int argc , int *argv[]){struct hostent *h;if(argc != 2)

    {fprintf(stderr , "usage : getip address \n ");exit(1);}if((h=gethostbyname(argv[1])) == NULL) /* Get the Local host name */{herror("gethostbyname ");exit(1);} printf(" Host name : %s \n ",h->h_name); printf("IP address : %s \n ", inet_ntoa(*((struct in_addr *)h->h_addr)));return 0;}

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    39/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to implement Client /Server architecture using UDP

    /*Program to implement Datagram server*/#include /*Usual header Files */

    #include #include #include #include #include #include #include #include #define MYPORT 4950 /* the port users will be connecting */#define MAXBUFLEN 100int main(void)

    {int sockfd;struct sockaddr_in my_addr; /* my address information*/struct sockaddr_in their_addr; /* connector’s address information*/int addr_len, numbytes;char buf[MAXBUFLEN];if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket");exit(1);}my_addr.sin_family = AF_INET; /* host byte order*/my_addr.sin_port = htons(MYPORT); // short, network byte order  my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IPmemset(&(my_addr.sin_zero), ’\0’, 8); // zero the rest of the structif (bind(sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1) { perror("bind");exit(1);}addr_len = sizeof(struct sockaddr);if ((numbytes=recvfrom(sockfd,buf, MAXBUFLEN-1, 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom");exit(1);} printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr)); printf("packet is %d bytes long\n",numbytes); buf[numbytes] = ’\0’; printf("packet contains \"%s\"\n",buf);close(sockfd);return 0; }

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    40/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Program to implement Datagram Client

    #include #include

    #include #include #include #include #include #include #include #include #define MYPORT 4950 // the port users will be connecting toint main(int argc, char *argv[]){

    int sockfd;struct sockaddr_in their_addr; // connector’s address informationstruct hostent *he;int numbytes;if (argc != 3) {fprintf(stderr,"usage: talker hostname message\n");exit(1);}if ((he=gethostbyname(argv[1])) == NULL) { // get the host info perror("gethostbyname");exit(1);}if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket");exit(1);}their_addr.sin_family = AF_INET; // host byte order  their_addr.sin_port = htons(MYPORT); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he->h_addr);memset(&(their_addr.sin_zero), ’\0’, 8); // zero the rest of the structif ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0,(struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) { perror("sendto");exit(1);} printf("sent %d bytes to %s\n", numbytes,inet_ntoa(their_addr.sin_addr));close(sockfd);return 0;}

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    41/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Procedure to run the program in LINUX

    1.Open VI editor (read the manual topic 1)

    2.Type the program.3.to save :wq4.To compile cc programname with extn5.to run ./a.out6.To get host name program ./a.out ipaddress of the system

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    42/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    SIMULATION OF ARP/RARP

    DATE: EX.NO: 1

    AIM:To perform Address Resolution Protocol or Reverse Address Resolution protocol using c.

    ALGORITHM:

    1. Start the program with required header files.

    2. To define file descriptor with characters, variables and character pointer.

    3. The MAC address and IP address are obtained from the user.

    4. To make The MAC and IP address is displayed as a table.

    5. Get the IP address from the user.

    6. ARP is used to Map the IP address and MAC Address and its display the MACaddress on the screen.

    7. Get the MAC address from the user.

    8. RARP used to Map the MAC address and IP address and its display the IP address on the

    screen.

    9. Stop.

    Sample Input: & Sample Output :

    Server File:

    Enter the MAC addressA1:B2:C3:D4:E5:F6

    Enter the IP address1.2.3.4

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    43/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    Enter the MAC addressA2.B3.C4.D5.E6.F7

    Enter the IP address5.6.7.8

    Enter the MAC addressA3.B4.C5.D6.E7.F8

    Enter the IP address9.10.11.12

    Client File:

    The APR table isA1.B2.C3.D4.E5.F6A2.B3.C4.D5.E6.F7A3.B4.C5.D6.E7.F8

    1.ARP2.RARP3.EXIT

    Enter your choice: 1

    Enter the IP address:

    5.6.7.8A2:B3:C4:D5:E6:f7

    Enter your choice 2

    Enter MAC addressA3:B4:C5:D6:E7:F89.10.11.12

    Result:Thus the program was executed successfully.

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    44/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    BITSTUFFING

    DATE: EX.NO: 2

    AIM:To write a C program to perform bit stuffing operation.

    ALGORITHM:

    1. Start the program with required header files.

    2. Get the input string from the user and find out the length of the string.

    3. Covert the given input string into ASCII character.

    4. Calculate the binary equivalent of each character.5. Check the number of ones present in the binary value.

    6. If there are five consecutive ones in the binary value then insert the parity bit in sixth

     position.

    7. Repeat the same procedure for entire string.

    8. Stop.

    Input:Enter the i/p string:

    10101111110101111110

    Output:

    The bit stuffed string is 1010111110101011111010

    Result:Thus the program was executed successfully.

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    45/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    CYCLIC REDUNDANCY CHECK (CRC)

    DATE: EX.NO: 3

    AIM:To write a C program to perform CRC.

    ALGORITHM:

    1. CRC is one of the powerful redundancies checking technique.

    2. Get the input form the user.

    3. Calculate the key value. Key k= number of bits present in the input – 1.

    4. The key using binary division technique divides the input string.5. The reminder is the required CRC it replaces the 0’s in the input string then transmits your 

    input.

    6. At the receiving end the key using binary division divides the received message.

    7. If reminder is 0 then your received message is correct otherwise it display the

    error message.

    Input & Output:

    1.find crc2.check crc3. exit

    Enter the choice 1Enter the input string

    100100Enter the key

    1101The transmitted message is 1001000011.find crc2. check crc3.exit

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    46/52

  • 8/9/2019 Network Lab Manual 2

    47/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    TRANSFERING FILES OVER RS232

    DATE: EX.NO: 4

    AIM:

    To write a c program to develop an application for transferring files over RS232

    ALGORITHM:

    1. Start the program by including all the necessary header files.2. Define the serial port base address.

    3. Turn off the interrupt using the output function.4. Set DLAB ON and band rates using the output function.5. Compile and execute the program.6. Enter your file name.7. Open the file in write mode else open the file in read mode.8. Stop.

    Input:

    Enter the file name: Sample.txtHi this is sample program

    Output:

    Sample.txtHi this is sample program

    Result:

    Thus the program was executed successfully.

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    48/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    SLIDING WINDOW PROTOCOL

    DATE: EX.NO: 5

    AIM:

    To write a C program to perform sliding window.

    ALGORITHM:

    1. Start the program.2. Get the frame size from the user 

    3. To create the frame based on the user request.4. To send frames to server from the client side.5. If your frames reach the server it will send ACK signal to client otherwise it will send NACK

    signal to client.6. Stop the program

    Input:

    Enter the frame size: 13Enter the number of frame: 2

    Output:

    ACK signal from server. NACK signal from server.

    Result:

    Thus the program was executed successfully.

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    49/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    CLIENT – SERVER APPLICATION FOR CHAT

    DATE: EX.NO: 6

    AIM:To write a C program for simple chat application.

    ALGORITHM:

    1. Start the program with the header files.

    2. To establish the connection between client and server by using socket and connectfunction.

    3. Bind the IP address and port number using bind function.4. To send data from client to server.5. The server provides the response to the client.6. Close the connection using close function.7. Stop.

    Input & Output:

    Server:[admin@root cse03]$./.a.out 16257Type the message to client:Hi how are youClient: hello how are you.Fine

    Client:

    [admin@root cse03]$. /.a.out 192.168.3.33 16257Enter the message to server Server: Hi how are you

    Hello how are you.Server: Fine

    Result:Thus the program was executed successfully.

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    50/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    DOMAIN NAME SYSTEM

    DATE: EX.NO: 7

    AIM:To write a C program to develop a DNS client server to resolve the given hostname.

    ALGORITHM:

    1. Create a new file. Enter the domain name and address in that file.2. To establish the connection between client and server.

    3. Compile and execute the program.4. Enter the domain name as input.5. The IP address corresponding to the domain name is display on the screen6. Enter the IP address on the screen.7. The domain name corresponding to the IP address is display on the screen.8. Stop the program.

    Input:

    [root@localhost root]# ./a.out 172.16.6.187

    Output:

    Hostname: 172.16.6.187Ip address:172.16.6.187

    Result:

    Thus the program was executed successfully

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    51/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    HTTP SERVER 

    DATE: EX.NO: 8

    AIM:

    To write a c program to download the file from HTTP server.

    ALGORITHM:

    1. Start the program by including the entire necessary header files.

    2. Initialize a file pointer named stream.3. Get the name of the HTML file from the user.4. Open the specified file in read mode.5. If the file pointer ‘stream’ is not NULL then get the character from the file and prin

    it.6. Stop the program.

    Input & Output:

    sample

    welcome to my home page

    Result:Thus the program was executed successfully

    http://csetube.tk/

    http://csetube.co.nr/http://csetube.co.nr/

  • 8/9/2019 Network Lab Manual 2

    52/52

       h

      t  t  p  :  /  /

      c  s  e  t  u   b

      e.  t   k  /

     Network Lab CS23

    NETWORK SIMULATOR 

    DATE: EX.NO: 9

    AIM:

    To write a program to perform network simulator using ping.

    ALGORITHM:

    1. Start the program.2. Create the required number of nodes and establish the connection between client and server.

    3. Give various transfer rates to nodes.4. Create the agent, which is used to check the connection between the nodes.5. Run the procedures and call the appropriate functions.6. Run the simulation.7. Check the output and stop the program.

    Result:

    Thus the program was executed successfully

    http://csetube.co.nr/http://csetube.co.nr/