144
(Kalasalingam Academy of Research and Education) Anand Nagar, Krishnankoil-626190. Dr.S.Radhakrishnan., HoD/CSE Mr.M.Gomathy Nayagam Ms.D.Kavitha Mr.B.Barnidharan Ms.M.Chitra

DCN LabManual

Embed Size (px)

Citation preview

(Kalasalingam Academy of Research and Education)Anand Nagar, Krishnankoil-626190.

Dr.S.Radhakrishnan., HoD/CSE Mr.M.Gomathy Nayagam Ms.D.Kavitha Mr.B.Barnidharan Ms.M.Chitra

Introduction Purpose of the Laboratory:The main goal of this laboratory is to give you a basic idea about the network related UNIX commands, different process involved to create a socket programming and the idea about to create client server based application using TCP or UDP protocol. After you completed this laboratory experiment, you should be familiar in socket programming, get a clear idea about the layered concept of network design and the protocols used in various layers, apply the concepts of routing and congestion in networks, able to know about cryptography and its applications in network security and get exposure in Internet and Web Technologies

Do's and Don'ts in the Lab:Do's Be punctual Wear the prescribed uniform. Remove the foot wares strictly. While entering the Lab, the students should sign in the student login register. Keep personal belonging in allotted place. Student should bring their ID card during the lab hour Submit the observation record of previous experiments. Students are allowed to do experiments only during lab hours. Use the allotted system and login as per the instruction only. Take the printouts regularly. While leaving the lab arrange the chairs you were sittings in the proper way. Help to maintain the lab clean.

Maintain strict discipline. Don'ts Dont use the system for typing letters, reports etc., during the lab hours.

2

Dont use others logins. Dont change the configurations/system settings. Dont bring floppies, CDs inside the lab without permission. Dont load unauthorized software.

Lesson Plan:Expt. No Name of the Experiment No of Periods Cumulative No of Periods

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11

Basic Unix Commands Introduction to Socket Programming Application for Client-Server Environment (TCP,UDP) Multicast Client/ Server Application Data Link Layer Operations Domain Name Service Getting the MAC Address HTTP Download Cryptography Remote Command Execution Remote Command Invocation Model Lab I

3 3 3 3 3 3 3 3 3 3 3 3

3 6 9 12 15 21 24 27 30 33 36 39

3

Lab Session: 1 Basic UNIX Commands Aim: To study the various basic and network related UNIX commands.

System and Software Requirements: PC with UNIX/ Linux Operating systems.

Basic UNIX/ Linux Commands and its PurposeBasic Commands S.NO COMMAND 1 man 2 pwd PURPOSE Shows help on a specific command. command prints the full pathname of your current working directory Shows you what directory you are in currently, your working directory. Lists your files ls l Lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified. ls -a Lists all files, including the ones whose filenames begin in a dot, which you do not always want to see. There are many more options, for example to list fFiles by size, by date, recursively etc. ls -al Lists files and directories in alphabetical order. ls -F Shows the difference between directories and ordinary files. Lists all your jobs that are currently running. Connects to your login directory cd . Takes you to the directory you're currently in. cd .. Connects to the directory one level up from the current

3

ls

4 5

alljobs cd

4

directory cd dirname Connects to the directory named dirname. 6

chmod

change the permissions of a file Symbol U G O A R W X + User Group Other All Read write (and delete) execute (and access directory) add permission take away permission Meaning

7

chgrp group-name filename

chmod go-rwx biglist to remove read write and execute permissions on the file biglist for the group and others, type Changes group affiliation of filename to group-name. chgrp -R group-name dirname Changes group affiliation of dirname and all files within dirname to group. make a new directory Removes the directory "dirname". Copies one file to another file. prints out the contents of a series of files one after the other prints out the contents of named files, one screen full at a time Displays file with minimal space. Creates a symbolic link from {source} to {dest}. Allows you to move around with ease instead of using long and complicated path names. command changes the name or location of a file or directorymv oldfile newfile

8 9 10 11 12 13 14 15

mkdir dirname rmdir dirname cp filename1 filename 2cat filename(1) filename(2)... filename(n) more filename(1) filename(2)... filename(n)

less filename ln -s {source} {dest} mv

5

mv file(1) file(2)... file(n) directory mv olddir newdir

16 17 18

diff file1 file2

cmp {file1} {file2} Rm

19 20 21 22 23 24 25 26 27 28 29 30

bp filename Cancel (ctrl)-z whoami date df -k quota v file filename(s) which {command} Whereis {command} wc filename find

ompares the contents of two files. Compares the contents of two files from each other. Reports the first different character found, and the line number. removes files and directories -i Inquire before removing a file -r Recursively remove a directory and all its contents and subdirectories A special SSC command that sends a file to the line printer in Bunche Hall. Terminates a command for a printer request. Hold down "Ctrl" key and "z" at the same time. Stops a job and puts it in the background returns your username. Displays the date and time. Shows disk space in Kbytes available on the system. Shows current disk usage and limits. Looks at "filename(s)" and tells what type of files they are. Reports the directory from which the {command} would be run if it was given as a command line argument. Reports the directory in which the {command} binary resides. tells you how many lines, words, and characters there are in a file Finds files and directory names. find -ls find -mtime 1 will list all files. will list files modified that day.

31 32 33 34 35 36 37 38 39

ff lprm lpstat lpq mime filename passwd ps public filename tail -30 filename

find files anywhere on the system Terminates a printer request. Reports the status of printer and jobs. Lists print spool. Encodes or decodes MIME64 files. Changes your password. You'll be asked to enter your old password Reports system processes. Makes files publically accessible Shows the last 30 lines of a file 6

40 41 42 43 44 45 46 47 48 49 50 51 52

who compress filename uncompress filename uuencode filename uudecode filename zip filename unzip filename.zip pine mail write username elm {login-name} source .logingrep

Shows who is logged onto the local system. Compressing your large datasets is useful when you're running out of disk space. Expands one or more files, created with compress, to their original form. Encodes file into ASCII text format in order to send through e-mail. Decodes files encoded in ASCII text format. Puts files into the .zip format. Reads files with the .zip extension. Starts the pine mail program. Sends and receives mail. lets you exchange one-line messages with another user Runs a screen oriented mail reader. With a "login-name", starts elm to send mail to "login-name". Otherwise, it starts elm for an interactive session. Runs your login file. Scans a file for the occurrence of a word or string and prints out any line in which it is found counts the lines, words and characters in a file -l Prints the number of lines in the files. -w Prints the number of words in the files. -c Prints the number of characters in the files Edits the file named filename with the Pico, an editor that is easy for new users to learn. Sets environment variables. Most frequently used to tell X which display you are on with "setenv DISPLAY displayname:0". Also used in .cshrc file to set "EDITOR" and "PRINTER" environment variables. This tells programs which editor you prefer, and which printer you want your output to be printed on. Prints out the values for all the current environment variables. Some typical environment variables are "DISPLAY", "EDITOR", and "PRINTER". Checks the spelling of the words in the standard input by default, checks words in "filename" if a name is supplied on the command line. If a word is misspelled it is printed to stdout ( usually the screen ). A compiler for the "C" programming language. "cc" is ANSI compatible on the SGI, IBM, and newer Sun machines. You might try also try "gcc", GNU CC, which is also available on the SGI, SUN, and IBM machines. A 7

wc [-l] [-w] [-c] filename...

53 54

pico filename setenv

55 56

env spell {filename}

57

cc

typical invocation might be "cc -g file.c -o executable name -llib". c++ {filename} A compiler for the C++ programming language. Command line parameters are similar to the "cc" compilers. A typical invocation might be "c++ -g file.cpp -o executable name -llib". X PostScript pre viewer. PostScript is a text processing and graphics language, and ghostview is handy for looking at the resulting page or picture before you send it to the printer. Anonymous local message center. File transfer program. Allows you to transfer files between computers - your PC at home to/from the computers at school, for instance. For more information, look in the online manual pages Runs the screen oriented network news program. Old and slow - maybe try "trn" or "tin". Threaded, full page network news reader . Quicker than vn. Threaded, full page network news reader. Easier than trn. Exits and disconnects your network connection. Clears the shell. Exits out of a shell.

58

ghostview {filename.ps} gossip kermit

59 60

61 62 63 64 65 66

vn Trn Tin logout Clear Exit

Network related commands:

1. netstatABOUT NETSTAT Shows network status SYNTAX netstat [-a] [-n] [-v] netstat [-g | -m | -p | -s | -f address_family ] [-n] [-P protocol] netstat [ -i ] [ -I interface ] [ interval ] netstat -r [-a] [-n] [-v ]

8

netstat -M [-n] [-s ] netstat -D [ -I interface ] -a Show the state of all sockets and all routing table entries; normally, sockets used by server processes are not shown and only interface, host, network, and default routes are shown. -n Show network addresses as numbers. netstat normally displays addresses as symbols. This option may be used with any of the display formats. -v Verbose. Show additional information for the sockets and the routing table. -g Show the multicast group memberships for all interfaces. -m Show the STREAMS statistics. -p Show the address resolution (ARP) tables. -s Show per-protocol statistics. When used with the -M option, show multicast routing statistics instead. -i Show the state of the interfaces that are used for TCP/IP traffic. -r Show the routing tables. -M Show the multicast routing tables. When used with the -s option, show multicast routing statistics instead. -d Show the state of all interfaces that are under Dynamic Host Configuration Protocol (DHCP) control. -D Show the status of DHCP configured interfaces. -f address_family imit statistics or address control block reports to those of the specified address_family, which can be one of: inet For the AF_INET address family unix For the AF_UNIX address family Limit display of statistics or state of all sockets to those applicable to protocol. Show the state of a particular interface. interface can be any valid interface such as ie0 or le0.

-P protocol - I interface

EXAMPLES netstat - displays generic net statistics of the host you are currently connected to.

2. ping9

ABOUT PING Sends ICMP ECHO_REQUEST packets to network hosts SYNTAX ping -s [-d] [-l] [-L] [-n] [-r] [-R] [-v] [ -i interface_address ] [-I interval] [-t ttl] host [packetsize] [count] -d -l Set the SO_DEBUG socket option. Loose source route. Use this option in the IP header to send the packet to the given host and back again. Usually specified with the -R option. -L Turn off loopback of multicast packets. Normally, if there are members in the host group on the out- going interface, a copy of the multicast packets will be delivered to the local machine. -n Show network addresses as numbers. ping normally displays addresses as host names. -r Bypass the normal routing tables and send directly to a host on an attached network. If the host is not on a directly-attached network, an error is returned. This option can be used to ping a local host through an interface that has been dropped by the router daemon. -R Record route. Sets the IP record route option, which will store the route of the packet inside the IP header. The contents of the record route will only be printed if the -v option is given, and only be set on return packets if the target host preserves the record route option across echos, or the -l option is given. -v Verbose output. List any ICMP packets, other than ECHO_RESPONSE, that are received. -I Specify the outgoing interface address to use for multicast packets. The interface_address default interface address for multicast packets is determined from the (unicast) routing tables. -I interval Specify the interval between successive transmissions. The default is one second. -t ttl Specify the IP time to live for unicast and multicast packets. The default time to live for unicast packets is set with ndd (using the icmp_def_ttl variable). The default time to live for multicast is one hop. Host The network host. Packetsize Specified size of packetsize. Default is 64. Count Amount of times to send the ping request. EXAMPLES ping computerhope.com - Would ping the host computerhope.com to see if it is alive.

10

Note: Many ISP's are disabling the ping command in helping to prevent possible Denial Of Service attacks. In addition some commands may not be available or results may vary when pinging a host.

3. telnetABOUT TELNET Uses the telnet protocol to connect to another remote computer. SYNTAX telnet [-8] [-E] [-L] [-c] [-d] [-r] [ -e escape_char ] [ -l user ] [-n file ] [ host [ port ] ] -8 -E -L -c -d -r Specifies an 8-bit data path. Negotiating the TELNET BINARY option is attempted for both input and output. Stops any character from being recognized as an escape character. Specifies an 8-bit data path on output. This causes the BINARY option to be negotiated on output. Disables the reading of the user's telnetrc file. Sets the initial value of the debug toggle to TRUE. Specifies a user interface similar to rlogin . In this mode, the escape character is set to the tilde (~) character, unless modified by the -e option. The rlogin escape character is only recognized when it is preceded by a carriage return. In this mode, the telnet escape character, normally '^]', must still precede a telnet command. The rlogin escape character can also be followed by '.\r' or '^Z', and, like rlogin, closes or suspends the connection, respectively. This option is an uncommitted inter- face and may change in the future. Sets the initial escape character to escape_char. escape_char may also be a two character sequence consisting of '^' followed by one character. If the second character is '?', the DEL character is selected. Otherwise, the second character is converted to a control character and used as the escape character. If the escape character is the null string (that is, -e ''), it is disabled. When connecting to a remote system that understands the ENVIRON option, then user will be sent to the remote system as the value for the ENVIRON variable USER. Opens tracefile for recording trace information.

-e escape_char

-l user

-n file

11

EXAMPLES telnet host.com - Would open a telnet session to the domain host.com

4. ifconfigABOUT The "ifconfig" command allows the operating system to setup network interfaces and allow the user to view information about the configured network interfaces. SYNTAX ifconfig [-L] [-m] interface [create] [address_family] [address[/prefixlength] [dest_address]] [parameters] ifconfig interface destroy ifconfig -a [-L] [-d] [-m] [-u] [address_family] ifconfig -l [-d] [-u] [address_family] ifconfig [-L] [-d] [-m] [-u] [-C] address For the DARPA-Internet family, the address is either a host name present in the host name data base, or a DARPA Internet address expressed in the Internet standard ``dot notation''. It is also possible to use the CIDR notation (also known as the slash notation) to include the netmask. That is, one can specify an address like 192.168.0.1/16. Specify the address family which affects interpretation of the remaining parameters. Since an interface can receive transmissions in differing protocols with different naming schemes, specifying the address family is recommended. The address or protocol families currently supported are ``inet'', ``inet6'', Specify the address of the correspondent on the other end of a point to point link. This parameter is a string of the form ``name unit'', for example, ``en0''. Another name for the alias parameter. Introduced for compatibility with BSD/OS. Establish an additional network address for this interface. This is sometimes useful when changing network numbers, and one wishes to accept packets addressed to the old interface. If the address is on the same subnet as the first network address for this interface, a netmask of 0xffffffff has to be specified. Remove the network address specified. This would be used if you incorrectly specified an alias, or it was no longer needed. If you have 12

addres_family

dest_address interface add alias

-alias

anycast

arp

-arp broadcast

debug -debug delete down

ether lladdr addr

media type

-mediaopt opts

incorrectly set an NS address having the side effect of specifying the host portion, removing all NS addresses will allow you to respecify the host portion. (Inet6 only.) Specify that the address configured is an anycast address. Based on the current specification, only routers may configure anycast addresses. Anycast address will not be used as source address of any of outgoing IPv6 packets. Enable the use of the Address Resolution Protocol in mapping between network level addresses and link level addresses (default). This is currently implemented for mapping between DARPA Internet addresses and IEEE 802 48-bit MAC addresses (Ethernet, FDDI, and Token Ring addresses). Disable the use of the Address Resolution Protocol (Inet only.) Specify the address to use to represent broadcasts to the network. The default broadcast address is the address with a host part of all 1's. Enable driver dependent debugging code; usually, this turns on extra console error logging. Disable driver dependent debugging code. Another name for the -alias parameter. Mark an interface ``down''. When an interface is marked ``down'', the system will not attempt to transmit messages through that interface. If possible, the interface will be reset to disable reception as well. This action does not automatically disable routes using the interface. Another name for the lladdr parameter. Set the link-level address on an interface. This can be used to e.g. set a new MAC address on an ethernet interface, though the mechanism used is not ethernet-specific. The address addr is specified as a series of colon-separated hex digits. If the interface is already up when this option is used, it will be briefly brought down and then brought back up again in order to ensure that the receive filter in the underlying ethernet hardware is properly reprogrammed. If the driver supports the media selection system, set the media type of the interface to type. Some interfaces support the mutually exclusive use of one of several different physical media connectors. For example, a 10Mb/s Ethernet interface might support the use of either AUI or twisted pair connectors. Setting the media type to ``10base5/AUI'' would change the currently active connector to the AUI port. Setting it to ``10baseT/UTP'' would activate twisted pair. Refer to the interfaces' driver specific documentation or man page for a complete list of the available types. If the driver supports the media selection system, set the specified media options on the interface. The opts argument is a comma delimited list of options to apply to the interface. Refer to the interfaces' 13

tunnel src_addr dest_addr

deletetunnel create

destroy plumb unplumb metric n

mtu n

netmask mask

prefixlen len

remove link[0-2]

driver specific man page for a complete list of available options. (IP tunnel devices only.) Configure the physical source and destination address for IP tunnel interfaces. The arguments src_addr and dest_addr are interpreted as the outer source/destination for the encapsulating IPv4/IPv6 header. Unconfigure the physical source and destination address for IP tunnel interfaces previously configured with tunnel. Create the specified network pseudo-device. If the interface is given without a unit number, try to create a new device with an arbitrary unit number. If creation of an arbitrary device is successful, the new device name is printed to standard output. Destroy the specified network pseudo-device. Another name for the create parameter. Included for Solaris compatibility. Another name for the destroy parameter. Included for Solaris compatibility. Set the routing metric of the interface to n, default 0. The routing metric is used by the routing protocol. Higher metrics have the effect of making a route less favorable; metrics are counted as addition hops to the destination network or host. Set the maximum transmission unit of the interface to n, default is interface specific. The MTU is used to limit the size of packets that are transmitted on an interface. Not all interfaces support setting the MTU, and some interfaces have range restrictions. (Inet only.) Specify how much of the address to reserve for subdividing networks into subnetworks. The mask includes the network part of the local address and the subnet part, which is taken from the host field of the address. The mask can be specified as a single hexadecimal number with a leading `0x', with a dot-notation Internet address, or with a pseudo-network name listed in the network table. The mask contains 1's for the bit positions in the 32-bit address which are to be used for the network and subnet parts, and 0's for the host part. The mask should contain at least the standard network portion, and the subnet field should be contiguous with the network portion. The netmask can also be specified in CIDR notation after the address. See the address option above for more information. (Inet6 only.) Specify that len bits are reserved for subdividing networks into sub-networks. The len must be integer, and for syntactical reason it must be between 0 to 128. It is almost always 64 under the current IPv6 assignment rule. If the parameter is omitted, 64 is used. Another name for the -alias parameter. Introduced for compatibility with BSD/OS. Enable special processing of the link level of the interface. These three options are interface specific in actual effect, how- ever, they are in 14

-link[0-2] up

general used to select special modes of operation. An example of this is to enable SLIP compression, or to select the connector type for some Ethernet cards. Refer to the man page for the specific driver for more information. Disable special processing at the link level with the specified interface. Mark an interface ``up''. This may be used to enable an interface after an ``ifconfig down''. It happens automatically when setting the first address on an interface. If the interface was reset when previously marked down, the hardware will be re-initialized.

EXAMPLES ifconfig eth0 - View the network settings on the first Ethernet adapter installed in the computer.

5. traceoutABOUT TRACEROUTE Print the route packets take to network host SYNTAX traceroute [-d] [-F] [-I] [-n] [-v] [-x] [-f first_ttl] [-g gateway [-g gateway] | -r] [-i iface] [-m max_ttl] [-p port] [-q nqueries] [-s src_addr] [-t tos] [-w waittime ] host [packetlen] -d -F -I -n Set the SO_DEBUG socket option. Set the "don't fragment" bit. Use ICMP ECHO instead of UDP datagrams. Print hop addresses numerically rather than symbolically and numerically. This saves a nameserver address-to-name lookup for each gateway found on the path. Verbose output. For each hop, the size and the destination of the response packets is displayed. Also ICMP packets received other than TIME_EXCEEDED and UNREACHABLE are listed as well. Prevent traceroute from calculating checksums. Note that checksums are usually required for the last hop when using ICMP ECHO probes. See the -I option. Set the starting ttl value to first_ttl, to override the default value 1. traceroute skips processing for those intermediate gateways which are less than first_ttl hops away.

-v

-x

-f first_ttl

15

-g gateway

-r

-i iface

-m max_ttl -p port

-q nqueries -s src_addr

-t tos

-w waittime host EXAMPLES

Specify a loose source route gateway. The user can specify more than one gateway by using -g for each gateway. The maximum that can be set is 8. Bypass the normal routing tables and send directly to a host on an attached network. If the host is not on a directly-attached network, an error is returned. This option can be used to send probes to a local host through an interface that has been dropped by the router deamon. Specify a network interface to obtain the source IP address for outgoing probe packets. This is normally only useful on a multi-homed host. The -s option is also another way to do this. Note that this option does not provide a way to specify the interface on which the probe packets are sent. Set the maximum ttl used in outgoing probe packets. The default is 30 hops, which is the same default used for TCP connections. Set the base UDP port number used in probes. The default is 33434. traceroute hopes that nothing is listening on UDP ports (base+(nhops1)*nqueries) to (base+(nhops*nqueries)-1)at the destination host, so that an ICMP PORT_UNREACHABLE message will be returned to terminate the route tracing. If something is listening on a port in the default range, this option can be used to select an unused port range.nhops is defined as the number of hops between the source and the destination. Set the desired number of probe queries. The default is 3. Use the following address, which usually is given as an IP address, not a hostname, as the source address in outgoing probe packets. On multihomed hosts, those with more than one IP address, this option can be used to force the source address to be something other than the IP address traceroute picks by default. If the IP address is not one of this machine's interface addresses, an error is returned and nothing is sent. When used together with the -i option, the given IP address should be configured on the specified interface. Otherwise, an error will be returned. Set the tos(type-of-service) in probe packets to the specified value. The default is zero. The value must be an integer in the range from 0 to 255. Gateways along the path may route the probe packet differently depending upon the tos value set in the probe packet. Set the time, in seconds, to wait for a response to a probe. The default is five (5) seconds. The network host.

traceroute computerhope.com - would display results similar to the following:

16

traceroute to computerhope.com (166.70.10.23), 30 hops max, 40 byte packets 1 198.60.22.1 (198.60.22.1) 2.303 ms 1.424 ms 2.346 ms 2 krunk3.xmission.com (198.60.22.6) 0.742 ms * 1.521 ms Exercise Questions for Lab Session-I 1. Refer Annexure- I 2. Refer Annexure-II 3. Refer Annexure-III

Lab Session: 2 Introduction to Socket Programming 2a. Socket Creation Aim: To create a program with socket for basic communication

System and Software Requirements: PC with UNIX/ Linux Operating systems. C compiler in Linux Environment

TheorySockets are interfaces that can "plug into" each other over a network. Once so "plugged in", the programs so connected communicate. A "server" program is exposed via a socket connected to a certain /etc/services port number. A "client" program can then connect its own socket to the server's socket, at which time the client program's writes to the socket are read as stdin to the server program, and stdout from the server program are read from the client's socket reads. This is one subset of socket programming, but it's perhaps the easiest to master, so this is where you should start.

There are different kinds of sockets available depending on which UNIX flavors we run. Some of them are: There are DARPA Internet addresses (Internet Sockets), path 17

names on a local node (Unix Sockets), CCITT X.25 addresses (X.25 Sockets that you can safely ignore). This document deals only with the first: Internet Sockets.Two Types of Internet Sockets:

One is Stream Sockets; the other is Datagram Sockets, which may hereafter be referred to as SOCK_STREAM and SOCK_DGRAM, respectively. Datagram sockets are sometimes called connectionless sockets. Stream sockets are reliable two-way connected communication streams. If you output two items into the socket in the order 1, 2, they will arrive in the order 1, 2 at the opposite end. They will also be error-free. What uses stream sockets? Well, you may have heard of the telnet application, yes? It uses stream sockets. All the characters you type need to arrive in the same order you type them, right? Also, web browsers use the HTTP protocol which uses stream sockets to get pages. Indeed, if you telnet to a web site on port 80, and type GET / HTTP/1.0 and hit RETURN twice, it'll dump the HTML back at you! How do stream sockets achieve this high level of data transmission quality? They use a protocol called The Transmission Control Protocol, otherwise known as TCP (see RFC 7936 for extremely detailed info on TCP.) TCP makes sure your data arrives sequentially and error-free. You may have heard TCP before as the better half of TCP/IP where IP stands for Internet Protocol (see RFC 7917.) IP deals primarily with Internet routing and is not generally responsible for data integrity. What about Datagram sockets? Why are they called connectionless? What is the deal, here, anyway? Why are they unreliable? Well, here are some facts: if you send a datagram, it may arrive. It may arrive out of order. If it arrives, the data within the packet will be error-free. Datagram sockets also use IP for routing, but they don't use TCP; they use the User Datagram Protocol, or UDP (see RFC 7688.) Why are they connectionless? Well, basically, it's because you don't have to maintain an open connection as you do with stream sockets. You just build a packet, slap an IP header on it with destination information, and send it out. No connection needed. They are generally used either when a TCP stack is unavailable or when a few dropped packets here and there don't mean the end of the Universe. Sample applications: tftp (trivial file transfer protocol, a little brother to FTP), dhcpcd (a DHCP client), multiplayer games, streaming audio, video conferencing, etc. tftp and dhcpcd are used to transfer binary applications from one host to another! Data can't be lost if you expect the application to work when it arrives! What kind of dark magic is this? tftp and similar programs have their own protocol on top of UDP. For example, the tftp protocol says that for each packet that gets sent, the recipient has to send back a packet that says, I got it! (an ACK packet.) If the sender of the original packet gets no reply in, say, five seconds, he'll retransmit the packet until he finally gets an ACK. This acknowledgment procedure is very important when implementing reliable SOCK_DGRAM applications. For unreliable applications like games, audio, or video, you just ignore the dropped packets, or perhaps try to cleverly compensate for them. (Quake players will know the manifestation this effect by the technical term: accursed lag. The word accursed, in this case, represents any extremely profane utterance.)

18

Why would you use an unreliable underlying protocol? Two reasons: speed and speed. It's way faster to fire-and-forget than it is to keep track of what has arrived safely and make sure it's in order and all that. If you're sending chat messages, TCP is great; if you're sending 40 positional updates per second of the players in the world, maybe it doesn't matter so much if one or two get dropped, and UDP is a good choice.

Low level Nonsense and Network TheoryIt's time to talk about how networks really work, and to show some examples of howSOCK_DGRAM packets are built. Practically, you can probably skip this section. It's good

background, however.

Data Encapsulation! This is very very important. Basically, it says this: a packet is born, the packet is wrapped (encapsulated) in a header (and rarely a footer) by the first protocol (say, the TFTP protocol), then the whole thing (TFTP header included) is encapsulated again by the next protocol (say, UDP), then again by the next (IP), then again by the final protocol on the hardware (physical) layer (say, Ethernet). When another computer receives the packet, the hardware strips the Ethernet header, the kernel strips the IP and UDP headers, the TFTP program strips the TFTP header, and it finally has the data. Now I can finally talk about the infamous Layered Network Model (aka ISO/OSI). This Network Model describes a system of network functionality that has many advantages over other models. For instance, you can write sockets programs that are exactly the same without caring how the data is physically transmitted (serial, thin Ethernet, AUI, whatever) because programs on lower levels deal with it for you. The actual network hardware and topology is transparent to the socket programmer. Without any further ado, I'll present the layers of the full-blown model. Remember this for network class exams: Application Presentation Session Transport Network Data Link Physical

19

The Physical Layer is the hardware (serial, Ethernet, etc.). The Application Layer is just about as far from the physical layer as you can imagineit's the place where users interact with the network. Now, this model is so general you could probably use it as an automobile repair guide if you really wanted to. A layered model more consistent with Unix might be: Application Layer (telnet, ftp, etc.) Host-to-Host Transport Layer (TCP, UDP) Internet Layer (IP and routing) Network Access Layer (Ethernet, wi-fi, or whatever) At this point in time, you can probably see how these layers correspond to the encapsulation of the original data. See how much work there is in building a simple packet? Jeez! And you have to type in the packet headers yourself using cat! Just kidding. All you have to do for stream sockets is send() the data out. All you have to do for datagram sockets is encapsulate the packet in the method of your choosing and sendto() it out. The kernel builds the Transport Layer and Internet Layer on for you and the hardware does the Network Access Layer. Ah, modern technology. So ends our brief foray into network theory. Oh yes, I forgot to tell you everything I wanted to say about routing: nothing! That's right, I'm not going to talk about it at all. The router strips the packet to the IP header, consults its routing table, blah blah blah. Check out the IP RFC9 if you really really care.

Procedure Used to Create Socketsocket (struct proc *p, struct socket_args *uap, int retval) struct sock_args { int domain, int type, int protocol; };

In the socket system call: p is a pointer to the proc structure of the process that makes the socket call. uap is a pointer to the socket_args structure that contains the arguments passed process in the socket system call. retval is the return value of the system call.

to the

The socket system call creates a new socket by assigning a new descriptor. The new descriptor is returned to the calling process. Any subsequent system calls are identified with the created socket. The socket system call also assigns the protocol to the created socket descriptor. In order to create a socket, we use the system call as, 20

int socketdescriptor = socket ( int domain, int type, int protocol); where domain specifies the name of the family to which socket belongs, type specifies the communication mode, protocol is one in which has the default value of zero. The return value is the integer value of which value can be greater than 3, then the socket cannot be created and there is error in the socket. Open one text editor with the help of gedit ,type the following code and stored it in the some filename (ex. Create.c) with extension c.

Algorithms Start the program. Include the necessary header files such as stdio.h and sys/socket.h Declare the socket descriptor. Using the socket system call to create a new socket (Both TCP and UDP). Check the return value of socket descriptor. If it is 0, then it is standard I/P else if it is 1, then it is standard O/P else if it is 2, then it is standard error. Display the return socket descriptor integer value. End the program.

Program#include #include int main() { printf (\n Socket Creation in C \n); int i_socketdescriptor; int i_sock; i_socketdescriptor = socket ( AF_INET, SOCK_STREAM,0); if(i_socketdescriptor == -1) { printf( Socket Descriptro : %d \n, i_socketdescriptor); printf(\n CREATION ERROR\n); } else { printf( Socket Descriptro : %d \n, i_socketdescriptor); printf(\n NO ERROR\n); } i_sock = socket (PF_INET, SOCK_DGRAM,0); if(i_sock == -1) { 21

printf( Socket Descriptor for PF_INET : %d \n, i_sock); printf(\n CREATION ERROR\n); } else { printf( Socket Descriptor for PF_INET : %d \n, i_sock); printf(\n CREATED SUCCESSFULLY\n); } }

How to Run the Program[root @ root] $ cc create.c [root @ root] $ ./a.out

OutputSocket Creation in C Socket Descriptor : 3 NO ERROR Socket Descriptor for PF-INET : 4 CREATED SUCCESSFULLY Exercises 1.Create UDP, TCP Sockets in Windows using JAVA programming. 2. Create UDP, TCP Sockets in windows using C Programming.

22

2b. Socket Binding Aim: To bind the socket to specified port for proper communication.

System and Software Requirements: PC with UNIX/ Linux Operating systems. C compiler in Linux Environment

TheoryThe bind() function associates a local address with a socket. Specifically, bind() assigns a local name to an unnamed socket. This routine is used on an unconnected datagram or stream socket, before a subsequent connect() or listen(). When socket() creates a socket, it exists in a name space (address family) but it has no name assigned. The bind() call requests that the name pointed to by name be assigned to the socket. The interpretation of name depends upon the address family of the socket. The syntax for bind of function is :#include #include int bind(int s, const struct sockaddr *name, socklen_t namelen);

where, s- Specifies the integer descriptor of the unbounded socket.name - Points to a sockaddr structure containing the address to be bound to the socket. The length and format of the address depend on the address family of the socket. namelen - Specifies the length of name in bytes.

RETURN VALUES:

23

If successful, bind() returns a value of zero. On failure, it returns -1 and sets errno to one of the following values: EACCES - For sockets in the AF_UNIX address family, the specified address does not specify a disk file local to the machine. For sockets in the AF_UNIX address family, a component of the path prefix denies search permission, or the requested name requires writing in a directory with a mode that denies write permission. EADDRINUSE -The specified address is already in use. [See the SO_REUSEADDR socket option under Stockpot(). EAFNOSUPPORT - The protocol used in the creation of specified socket does not support the specified address family. EBADF - s is not a valid descriptor. EFAULT - name is an invalid pointer or the namelen parameter is too small (less than the size of a struct sockaddr). EINVAL - The socket is already bound to an address. ENETDOWN - The Windows sockets implementation has detected that the network subsystem has failed. ENOBUFS - Not enough buffers are available; there are too many connections. ENOTSOCK - The descriptor is not a socket.

Algorithms Start the program. Include necessary header file such as sys/socket.h, sys/types.h and netinet/in.h. Create the socket with the system call socket() and assigned to some socket descriptor. Check the socket descriptor value for proper creation. Describe the structure with family, port number and IP address. Bind the socket and port number with the system call bind(). Check the socket and port number are properly bound or not. Print the bind value and port number on the screen. End the Program.

Program#include #include #include #include int main() { int isocketdescriptor, iBindValue; struct sockeaddr_in sAddr; isocketdescriptor = socket (AF_INET, SOCK_STREAM,0);

24

if (isocketdescriptor h_addr); bzero(&(server_addr.sin_zero),8); if(connect(sock,(struct sockaddr*)&server_addr,sizeof(struct sockaddr))==-1) { perror("Connect"); exit(1); } while(1) { by_recv=recv(sock,recv_data,1024,0); recv_data[by_recv]='\0'; if(strcmp(recv_data,"q")==0||strcmp(recv_data,"Q")==0) { close(sock); break; } else printf("\n RECIVED DATA=%s",recv_data); printf("\n SEND(q or Q to quit):"); gets(send_data); if(strcmp(send_data,"q")==0||strcmp(send_data,"Q")!=0) send(sock,send_data,strlen(send_data),0); else { send(sock,send_data,strlen(send_data),0); close(sock); break; }

43

} return 0; }

Server#include #include #include #include #include #include #include #include #include int main() { int sock,con,by_rec,true=1; char send_data[1024],recv_data[1024]; struct sockaddr_in server_addr,cli_addr; int sin_size; if((sock=socket(AF_INET,SOCK_STREAM,0))==-1) { perror("socket"); exit(1); } if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))==-1) { perror("setsockopt"); exit(1); } server_addr.sin_family=AF_INET; server_addr.sin_port=htons(5000); server_addr.sin_addr.s_addr=INADDR_ANY; bzero(&(server_addr.sin_zero),8); if(bind(sock,(struct sockaddr*)&server_addr,sizeof(struct sockaddr))==1) { perror("unable to bind"); exit(1); } if(listen(sock,5)==-1) { perror("Listen"); exit(1); } printf("\n TCP Server waiting for client on port 5000"); fflush(stdout); while(1) { sin_size=sizeof(struct sockaddr_in); con=accept(sock,(struct sockaddr*)&cli_addr,&sin_size); printf("\n I got a connection from(%s, %d)",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port)); while(1) {

44

printf("\n SEND(q or Q to quit):"); gets(send_data); if(strcmp(send_data,"q")==0||strcmp(send_data,"Q")==0) { send(con,send_data,strlen(send_data),0); close(con); break; } else send(con,send_data,strlen(send_data),0); by_rec=recv(con,recv_data,1024,0); recv_data[by_rec]='\0'; if(strcmp(recv_data,"q")==0||strcmp(recv_data,"Q")==0) { close(con); break; } else printf("\n RECIVED DATA=%s",recv_data); fflush(stdout); } } close(sock); return 0; }

How to Run the Server Program[root @ root] $ cc server.c [root @ root] $ ./a.out

Output of the Server ProgramServer Program ************************** Socket created successfully Socket descriptor value: 3 ************************** Successful Binding Bind desc : 0 IP Address : 0.0.0.0 ************************* Processor is in Listener Mode Message is sent *************************

How to Run the Client Program[root @ root] $ cc client.c [root @ root] $ ./a.out

45

Output of the Client ProgramClient program Socket created Socket descriptor value:3 Connected to the server Message is received

Lab Session: 3 Application for Client-Server Environment (TCP,UDP) 3a. File Transfer Between Client and Server Using FTP

Aim: To Transfer the file between client and server using Transmission Control Protocol.

System and Software Requirements: PC with UNIX/ Linux Operating systems. C compiler in Linux Environment

TheoryThe purpose of networking applications is to allow different types of information to be sent between networked devices. In the world of computers, information is most often arranged into discrete units called files. When those files are created specifically for the purpose of communication, they are often called messages. One of the most important groups of TCP/IP applications is the one that describes the basic mechanisms for moving these files between inter networked devices: file and message transfer applications. File Transfer Protocol (FTP) is a standard network protocol used to exchange and manipulate files over a TCP/IP based network, such as the Internet. FTP is built on a client-server architecture and utilizes separate control and data connections between the client and server applications. Applications were originally interactive command-line tools with a standardized command syntax, but graphical user interfaces have been developed for all desktop operating systems in use today. FTP is also often used as an 46

application component to automatically transfer files for program internal functions. FTP can be used with user-based password authentication or with anonymous user access. The Trivial File Transfer Protocol (TFTP) is a similar, but simplified, not interoperable, and unauthenticated version of FTP. Open() open - open a file

SYNOPSIS #include #include #include int open(const char *path, int oflag, ... ); DESCRIPTION The open() function establishes the connection between a file and a file descriptor. It creates an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file. The open() function will return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor does not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor will be cleared. The file offset used to mark the current position within the file is set to the beginning of the file. The file status flags and file access modes of the open file description will be set according to the value of oflag.

47

Values for oflag are constructed by a bitwise-inclusive-OR of flags from the following list, defined in . Applications must specify exactly one of the first three values (file access modes) below in the value of oflag: O_RDONLY Open for reading only. O_WRONLY Open for writing only. O_RDWR Open for reading and writing. The result is undefined if this flag is applied to a FIFO. Any combination of the following may be used: O_APPEND If set, the file offset will be set to the end of the file prior to each write. O_CREAT If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file is created; the user ID of the file is set to the effective user ID of the process; the group ID of the file is set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see ) of the file mode are set to the value of the third argument taken as type mode_t modified as follows: a bitwise-AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing or for both. O_DSYNC Write I/O operations on the file descriptor complete as defined by synchronised I/O data integrity completion O_EXCL

48

If O_CREAT and O_EXCL are set, open() will fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist will be atomic with respect to other processes executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_CREAT is not set, the effect is undefined. O_NOCTTY If set and path identifies a terminal device, open() will not cause the terminal device to become the controlling terminal for the process. O_NONBLOCK When opening a FIFO with O_RDONLY or O_WRONLY set: If O_NONBLOCK is set: An open() for reading only will return without delay. An open() for writing only will return an error if no process currently has the file open for reading. If O_NONBLOCK is clear: An open() for reading only will block the calling thread until a thread opens the file for writing. An open() for writing only will block the calling thread until a thread opens the file for reading. When opening a block special or character special file that supports non-blocking opens: If O_NONBLOCK is set: or The open() function will return without blocking for the device to be ready available. Subsequent behaviour of the device is device-specific. If O_NONBLOCK is clear: or The open() function will block the calling thread until the device is ready available before returning. Otherwise, the behaviour of O_NONBLOCK is unspecified. O_RSYNC Read I/O operations on the file descriptor complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor complete as defined by synchronised I/O data integrity completion. If both O_SYNC and

49

O_RSYNC are set in flags, all I/O operations on the file descriptor complete as defined by synchronised I/O file integrity completion. O_SYNC Write I/O operations on the file descriptor complete as defined by synchronised I/O file integrity completion. O_TRUNC If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length is truncated to 0 and the mode and owner are unchanged. It will have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-dependent. The result of using O_TRUNC with O_RDONLY is undefined. If O_CREAT is set and the file did not previously exist, upon successful completion, open() will mark for update the st_atime, st_ctime and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory. If O_TRUNC is set and the file did previously exist, upon successful completion, open() will mark for update the st_ctime and st_mtime fields of the file. If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set. If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR-ed with either O_RDONLY, O_WRONLY or O_RDWR. Other flag values are not applicable to STREAMS devices and have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific. If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Portable applications must call unlockpt() before opening the slave side. The largest value that can be represented correctly in an object of type off_t will be established as the offset maximum in the open file description. RETURN VALUE Upon successful completion, the function will open the file and return a nonnegative integer representing the lowest numbered unused file descriptor. Otherwise, -1 is returned and errno is set to indicate the error. No files will be created or modified if the function returns -1.

50

ERRORS The open() function will fail if: [EACCES] Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by oflag are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, or O_TRUNC is specified and write permission is denied. [EEXIST] O_CREAT and O_EXCL are set, and the named file exists. [EINTR] A signal was caught during open(). [EINVAL] The implementation does not support synchronised I/O for this file. [EIO] The path argument names a STREAMS file and a hangup or error occurred during the open(). [EISDIR] The named file is a directory and oflag includes O_WRONLY or O_RDWR. [ELOOP] Too many symbolic links were encountered in resolving path. [EMFILE] {OPEN_MAX} file descriptors are currently open in the calling process. [ENAMETOOLONG] The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

51

[ENFILE] The maximum allowable number of files is currently open in the system. [ENOENT] O_CREAT is not set and the named file does not exist; or O_CREAT is set and either the path prefix does not exist or the path argument points to an empty string. [ENOSR] The path argument names a STREAMS-based file and the system is unable to allocate a STREAM. [ENOSPC] The directory or file system that would contain the new file cannot be expanded, the file does not exist, and O_CREAT is specified. [ENOTDIR] A component of the path prefix is not a directory. [ENXIO] O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set and no process has the file open for reading. [ENXIO] The named file is a character special or block special file, and the device associated with this special file does not exist. [EOVERFLOW] The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t. [EROFS] The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT (if file does not exist) or O_TRUNC is set in the oflag argument. The open() function may fail if:

52

[EAGAIN] The path argument names the slave side of a pseudo-terminal device that is locked. [EINVAL] The value of the oflag argument is not valid. [ENAMETOOLONG] Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. [ENOMEM] The path argument names a STREAMS file and the system is unable to allocate resources. [ETXTBSY] The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR. Read() read, readv, pread - read from a file SYNOPSIS #include ssize_t read(int fildes, void *buf, size_t nbyte); ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset); #include ssize_t readv(int fildes, const struct iovec *iov, int iovcnt); DESCRIPTION The read() function attempts to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. If nbyte is 0, read() will return 0 and have no other results.

53

On files that support seeking (for example, a regular file), the read() starts at a position in the file given by the file offset associated with fildes. The file offset is incremented by the number of bytes actually read. Files that do not support seeking, for example, terminals, always read from the current position. The value of a file offset associated with such a file is undefined. No data transfer will occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 will be returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-dependent. If the value of nbyte is greater than {SSIZE_MAX}, the result is implementationdependent. When attempting to read from an empty pipe or FIFO:

If no process has the pipe open for writing, read() will return 0 to indicate end-offile. If some process has the pipe open for writing and O_NONBLOCK is set, read() will return -1 and set errno to [EAGAIN]. If some process has the pipe open for writing and O_NONBLOCK is clear, read() will block the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing.

When attempting to read a file (other than a pipe or FIFO) that supports nonblocking reads and has no data currently available:

If O_NONBLOCK is set, read() will return a -1 and set errno to [EAGAIN]. If O_NONBLOCK is clear, read() will block the calling thread until some data becomes available. The use of the O_NONBLOCK flag has no effect if there is some data available.

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() returns bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads in the gap between the previous end of data and the newly written data will return bytes with value 0 until data is written into the gap. Upon successful completion, where nbyte is greater than 0, read() will mark for update the st_atime field of the file, and return the number of bytes read. This number will never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.

54

If a read() is interrupted by a signal before it reads any data, it will return -1 with errno set to [EINTR]. If a read() is interrupted by a signal after it has successfully read some data, it will return the number of bytes read. A read() from a STREAMS file can read data in three different modes: bytestream mode, message-nondiscard mode, and message-discard mode. The default is bytestream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested with the I_GRDOPT ioctl(). In byte-stream mode, read() retrieves data from the STREAM until as many bytes as were requested are transferred, or until there is no more data to be retrieved. Byte-stream mode ignores message boundaries. In STREAMS message-nondiscard mode, read() retrieves data until as many bytes as were requested are transferred, or until a message boundary is reached. If read() does not retrieve all the data in a message, the remaining data is left on the STREAM, and can be retrieved by the next read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a message after the read() returns is discarded, and is not available for a subsequent read(), readv() or getmsg() call. How read() handles zero-byte STREAMS messages is determined by the current read mode setting. In byte-stream mode, read() accepts data until it has read nbyte bytes, or until there is no more data to read, or until a zero-byte message block is encountered. The read() function then returns the number of bytes read, and places the zero-byte message back on the STREAM to be retrieved by the next read(), readv() or getmsg(). In message-nondiscard mode or message-discard mode, a zero-byte message returns 0 and the message is removed from the STREAM. When a zero-byte message is read as the first message on a STREAM, the message is removed from the STREAM and 0 is returned, regardless of the read mode. A read() from a STREAMS file returns the data in the message at the front of the STREAM head read queue, regardless of the priority band of the message. By default, STREAMs are in control-normal mode, in which a read() from a STREAMS file can only process messages that contain a data part but do not contain a control part. The read() fails if a message containing a control part is encountered at the STREAM head. This default action can be changed by placing the STREAM in either control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In control-data mode, read() converts any control part to data and passes it to the application before passing any data part originally present in the same message. In control-discard mode, read() discards message control parts but returns to the process any data part in the message. In addition, read() and readv() will fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno does not reflect the

55

result of read() or readv() but reflects the prior error. If a hangup occurs on the STREAM being read, read() continues to operate normally until the STREAM head read queue is empty. Thereafter, it returns 0. The readv() function is equivalent to read(), but places the input data into the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1]. The iovcnt argument is valid if greater than 0 and less than or equal to {IOV_MAX}. Each iovec entry specifies the base address and length of an area in memory where data should be placed. The readv() function always fills an area completely before proceeding to the next. Upon successful completion, readv() marks for update the st_atime field of the file. If the Synchronized Input and Output option is supported: If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor complete as defined by synchronised I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor complete as defined by synchronised I/O file integrity completion. If the Shared Memory Objects option is supported: If fildes refers to a shared memory object, the result of the read() function is unspecified. For regular files, no data transfer will occur past the offset maximum established in the open file description associated with fildes. The pread() function performs the same action as read(), except that it reads from a given position in the file without changing the file pointer. The first three arguments to pread() are the same as read() with the addition of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking results in an error. RETURN VALUE Upon successful completion, read(), pread() and readv() return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions return -1 and set errno to indicate the error. ERRORS The read(), pread() and readv() functions will fail if:

56

[EAGAIN] The O_NONBLOCK flag is set for the file descriptor and the process would be delayed. [EBADF] The fildes argument is not a valid file descriptor open for reading. [EBADMSG] The file is a STREAM file that is set to control-normal mode and the message waiting to be read includes a control part.

[EINTR] The read operation was terminated due to the receipt of a signal, and no data was transferred. [EINVAL] The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer. [EIO] A physical I/O error has occurred. [EIO] The process is a member of a background process attempting to read from its controlling terminal, the process is ignoring or blocking the SIGTTIN signal or the process group is orphaned. This error may also be generated for implementation-dependent reasons. [EISDIR] The fildes argument refers to a directory and the implementation does not allow the directory to be read using read(), pread() or readv(). The readdir() function should be used instead. [EOVERFLOW]

57

The file is a regular file, nbyte is greater than 0, the starting position is before the end-of-file and the starting position is greater than or equal to the offset maximum established in the open file description associated with fildes. The readv() function will fail if: [EINVAL] The sum of the iov_len values in the iov array overflowed an ssize_t. The read(), pread() and readv() functions may fail if: [ENXIO] A request was made of a non-existent device, or the request was outside the capabilities of the device. The readv() function may fail if: [EINVAL] The iovcnt argument was less than or equal to 0, or greater than {IOV_MAX}. The pread() function will fail, and the file pointer remains unchanged, if: [EINVAL] The offset argument is invalid. The value is negative. [EOVERFLOW] The file is a regular file and an attempt was made to read or write at or beyond the offset maximum associated with the file. [ENXIO] A request was outside the capabilities of the device. [ESPIPE] fildes is associated with a pipe or FIFO Read()

58

write, writev, pwrite - write on a file

SYNOPSIS#include ssize_t write(int fildes, const void *buf, size_t nbyte); ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset); #include ssize_t writev(int fildes, const struct iovec *iov, int iovcnt);

DESCRIPTIONThe write() function attempts to write nbyte bytes from the buffer pointed to by buf to the file associated with the open file descriptor, fildes. If nbyte is 0, write() will return 0 and have no other results if the file is a regular file; otherwise, the results are unspecified. On a regular file or other file capable of seeking, the actual writing of data proceeds from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset is incremented by the number of bytes actually written. On a regular file, if this incremented file offset is greater than the length of the file, the length of the file will be set to this file offset. On a file not capable of seeking, writing always takes place starting at the current position. The value of a file offset associated with such a device is undefined. If the O_APPEND flag of the file status flags is set, the file offset will be set to the end of the file prior to each write and no intervening file modification operation will occur between changing the file offset and the write operation. If a write() requests that more bytes be written than there is room for (for example, the ulimit or the physical end of a medium), only as many bytes as there is room for will be written. For example, suppose there is space for 20 bytes more in a file before reaching a limit. A write of 512 bytes will return 20. The next write of a non-zero number of bytes will give a failure return (except as noted below) and the implementation will generate a SIGXFSZ signal for the thread. If write() is interrupted by a signal before it writes any data, it will return -1 with errno set to [EINTR]. If write() is interrupted by a signal after it successfully writes some data, it will return the number of bytes written. If the value of nbyte is greater than {SSIZE_MAX}, the result is implementationdependent.

59

After a write() to a regular file has successfully returned:

Any successful read() from each byte position in the file that was modified by that write will return the data specified by the write() for that position until such byte positions are again modified. Any subsequent successful write() to the same byte position in the file will overwrite that file data.

Write requests to a pipe or FIFO will be handled the same as a regular file with the following exceptions:

There is no file offset associated with a pipe, hence each write request will append to the end of the pipe. Write requests of {PIPE_BUF} bytes or less will not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set. If the O_NONBLOCK flag is clear, a write request may cause the thread to block, but on normal completion it will return nbyte. If the O_NONBLOCK flag is set, write() requests will be handled differently, in the following ways: o The write() function will not block the thread. o A write request for {PIPE_BUF} or fewer bytes will have the following effect: If there is sufficient space available in the pipe, write() will transfer all the data and return the number of bytes requested. Otherwise, write() will transfer no data and return -1 with errno set to [EAGAIN]. o A write request for more than {PIPE_BUF} bytes will case one of the following: a. When at least one byte can be written, transfer what it can and return the number of bytes written. When all data previously written to the pipe is read, it will transfer at least {PIPE_BUF} bytes. b. When no data can be written, transfer no data and return -1 with errno set to [EAGAIN].

When attempting to write to a file descriptor (other than a pipe or FIFO) that supports non-blocking writes and cannot accept the data immediately:

If the O_NONBLOCK flag is clear, write() will block the calling thread until the data can be accepted. If the O_NONBLOCK flag is set, write() will not block the process. If some data can be written without blocking the process, write() will write what it can and return the number of bytes written. Otherwise, it will return -1 and errno will be set to [EAGAIN].

60

Upon successful completion, where nbyte is greater than 0, write() will mark for update the st_ctime and st_mtime fields of the file, and if the file is a regular file, the S_ISUID and S_ISGID bits of the file mode may be cleared. If fildes refers to a STREAM, the operation of write() is determined by the values of the minimum and maximum nbyte range ("packet size") accepted by the STREAM. These values are determined by the topmost STREAM module. If nbyte falls within the packet size range, nbyte bytes will be written. If nbyte does not fall within the range and the minimum packet size value is 0, write() will break the buffer into maximum packet size segments prior to sending the data downstream (the last segment may contain less than the maximum packet size). If nbyte does not fall within the range and the minimum value is non-zero, write() will fail with errno set to [ERANGE]. Writing a zero-length buffer (nbyte is 0) to a STREAMS device sends 0 bytes with 0 returned. However, writing a zero-length buffer to a STREAMS-based pipe or FIFO sends no message and 0 is returned. The process may issue I_SWROPT ioctl() to enable zero-length messages to be sent across the pipe or FIFO. When writing to a STREAM, data messages are created with a priority band of 0. When writing to a STREAM that is not a pipe or FIFO:

If O_NONBLOCK is clear, and the STREAM cannot accept data (the STREAM write queue is full due to internal flow control conditions), write() will block until data can be accepted. If O_NONBLOCK is set and the STREAM cannot accept data, write() will return -1 and set errno to [EAGAIN]. If O_NONBLOCK is set and part of the buffer has been written while a condition in which the STREAM cannot accept additional data occurs, write() will terminate and return the number of bytes written.

In addition, write() and writev() will fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno does not reflect the result of write() or writev() but reflects the prior error. The writev() function is equivalent to write(), but gathers the output data from the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1]. iovcnt is valid if greater than 0 and less than or equal to {IOV_MAX}, defined in . Each iovec entry specifies the base address and length of an area in memory from which data should be written. The writev() function will always write a complete area before proceeding to the next. If fildes refers to a regular file and all of the iov_len members in the array pointed to by iov are 0, writev() will return 0 and have no other effect. For other file types, the behaviour is unspecified.

61

If the sum of the iov_len values is greater than SSIZE_MAX, the operation fails and no data is transferred. If the Synchronized Input and Output option is supported: If the O_DSYNC bit has been set, write I/O operations on the file descriptor complete as defined by synchronised I/O data integrity completion. If the O_SYNC bit has been set, write I/O operations on the file descriptor complete as defined by synchronised I/O file integrity completion. If the Shared Memory Objects option is supported: If fildes refers to a shared memory object, the result of the write() function is unspecified. For regular files, no data transfer will occur past the offset maximum established in the open file description associated with fildes. The pwrite() function performs the same action as write(), except that it writes into a given position without changing the file pointer. The first three arguments to pwrite() are the same as write() with the addition of a fourth argument offset for the desired position inside the file.

RETURN VALUEUpon successful completion, write() and pwrite() will return the number of bytes actually written to the file associated with fildes. This number will never be greater than nbyte. Otherwise, -1 is returned and errno is set to indicate the error. Upon successful completion, writev() returns the number of bytes actually written. Otherwise, it returns a value of -1, the file-pointer remains unchanged, and errno is set to indicate an error.

ERRORSThe write(), writev() and pwrite() functions will fail if: [EAGAIN] The O_NONBLOCK flag is set for the file descriptor and the thread would be delayed in the write() operation. [EBADF] The fildes argument is not a valid file descriptor open for writing. [EFBIG] An attempt was made to write a file that exceeds the implementationdependent maximum file size or the process' file size limit. [EFBIG]

62

The file is a regular file, nbyte is greater than 0 and the starting position is greater than or equal to the offset maximum established in the open file description associated with fildes. [EINTR] The write operation was terminated due to the receipt of a signal, and no data was transferred. [EIO] A physical I/O error has occurred. [EIO] The process is a member of a background process group attempting to write to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU and the process group of the process is orphaned. This error may also be returned under implementation-dependent conditions. [ENOSPC] There was no free space remaining on the device containing the file.

[EPIPE] An attempt is made to write to a pipe or FIFO that is not open for reading by any process, or that only has one end open. A SIGPIPE signal will also be sent to the thread. [ERANGE] The transfer request size was outside the range supported by the STREAMS file associated with fildes. The writev() function will fail if: [EINVAL] The sum of the iov_len values in the iov array would overflow an ssize_t. The write(), writev() and pwrite() functions may fail if: [EINVAL] The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer. [ENXIO] A request was made of a non-existent device, or the request was outside the capabilities of the device. [ENXIO] A hangup occurred on the STREAM being written to. A write to a STREAMS file may fail if an error message has been received at the STREAM head. In this case, errno is set to the value included in the error message. The writev() function may fail and set errno to:

63

[EINVAL] The iovcnt argument was less than or equal to 0, or greater than {IOV_MAX}. The pwrite() function fails and the file pointer remains unchanged if: [EINVAL] The offset argument is invalid. The value is negative. [ESPIPE] fildes is associated with a pipe or FIFO.

Algorithms Client Start the program Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h Create socket with the system call socket() for establishing connection and assigned some socket descriptor. Check the socket descriptor value for proper creation. Describe the structure with family, port number and IP address. Bind the socket and port number with the system call bind() Check the socket and port number are properly bound or not. Create a new file in write mode for storing the received content from server. Write the content in file. End the program.

Server Start the program Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h Create socket with the system call socket() for establishing connection and assigned some socket descriptor. Check the socket descriptor value for proper creation. Describe the structure with family, port number and IP address. Bind the socket and port number with the system call bind() Check the socket and port number are properly bound or not. Using the system call listen() for listening request coming from client by server and it will return some integer value. If the returned integer value is -1, then the server is not listening. Open a file which is requested by the client in read mode. Send the file content as a stream to client.

64

End the program.

Program Server

#include #include #include #include int main() { int i_sd,i_bind,i_size,i_acc,i_send,i_lis,fd; char *buff[100]; FILE *fp; printf("server program\n"); printf("************************************\n"); struct sockaddr_in server; struct sockaddr_in client; i_sd=socket(AF_INET,SOCK_STREAM,0); if(-1==i_sd) { printf(" creation error\n"); printf(" socket descriptor value:%d\n",i_sd); } else printf("socket created successfully\n"); printf("socket descriptor value:%d\n",i_sd); printf("************************************\n"); server.sin_family=AF_INET; server.sin_port=htons(2006); server.sin_addr.s_addr=htonl(INADDR_ANY); bzero(server.sin_zero,8); i_bind=bind(i_sd,(struct sockaddr*)&server,sizeof(struct sockaddr_in)); if(-1==i_bind) { printf("\n binding error\n"); printf("bind desc:%d\n",i_bind); } else { printf("successfully binding\n"); printf("bind desc:%d\n",i_bind); } printf("IP ADDRESS :%s\n",inet_ntoa(server.sin_addr)); printf("*******************************************\n"); i_lis=listen(i_sd,3); if(-1==i_lis) { printf("\n error\n"); exit(0); } else { printf("\n processor is in listener mode\n");

65

} i_size=sizeof(struct sockaddr_in); i_acc=accept(i_sd,(struct sockaddr*)&client,&(i_size)); if(-1==i_acc) { printf("\n error\n"); } else { printf("\n listener is accepted\n"); fd=open("san.txt","O_RDWR"); while(read(fd,buff,100)>0) { i_send=send(i_acc,buff,100,0); if(-1==i_send) printf("\nerror\n"); } } }

Client

#include #include #include #include #include #include int main(int argc,char *agrv[]) { int i_sd,i_bind,i_conn,sadd,i_rec,i_recv,fd; char *str[100]; FILE *fp; printf("client program\n"); printf("************************\n"); struct sockaddr_in client; i_sd=socket(AF_INET,SOCK_STREAM,0); if(-1==i_sd) { printf("creation error\n"); printf("socket descriptor value:%d\n",i_sd); } else { printf("socket created successfully\n"); printf("socket descriptor value:%d\n",i_sd); printf("*******************************\n"); client.sin_family=AF_INET; client.sin_port=htons(3001); client.sin_addr.s_addr=inet_addr("127.0.0.1"); bzero(client.sin_zero,8); i_bind=connect(i_sd,(struct sockaddr*)&client,sizeof(struct sockaddr)); if(1==i_bind) { printf("binding error\n");

66

} else { printf("connected to server\n"); } printf("********************************\n"); fd=open("chan.txt",O_RDWR); while(recv(i_sd,str,100,0)) { if(-1==i_rec) { printf("\nerror\n"); exit(0); } else { write(fd,str,100); } } } }

How to Run the Server Program[root @ root] $ cc server.c [root @ root] $ ./a.out

Output of the Server ProgramServer Program ************************** Socket created successfully Socket descriptor value: 3 ************************** Successful Binding Bind desc : 0 IP Address : 0.0.0.0 ************************* Processor is in Listener Mode Message is sent *************************

How to Run the Client Program[root @ root] $ cc server.c [root @ root] $ ./a.out

Output of the Client ProgramClient program Socket created Socket descriptor value:3 Connected to the server

67

Message is received

Lab Session: 6 Domain Name Services (DNS)

Aim: To domain name service using UDP protocol.

System and Software Requirements: PC with UNIX/ Linux Operating systems. C compiler in Linux Environment

TheoryEvery host that runs TCP/IP must have a unique IP address that's used when communicating with other computers in a network. Computers operate easily with IP addresses, but people don't; users would rather identify systems by a name. To facilitate effective and efficient communication, users need to be able to refer to computers by name, and still have their computer use IP addresses transparently. The Domain Name System (DNS) is a hierarchical naming system for computers, services, or any resource connected to the Internet or a private network. It associates various information with domain names assigned to each of the participants. Most importantly, it translates domain names meaningful to humans into the numerical (binary) identifiers associated with networking equipment for the purpose of locating and addressing these devices worldwide. An often used analogy to explain the Domain Name System is that it serves as the "phone book" for the Internet by translating human-friendly

68

computer hostnames into IP addresses. For example, www.example.com translates to 192.0.32.10. In the early days of the ARPANET, the forerunner to today's Internet, there were only a small number of computers attached to the network. The Network Information Center (NIC), located at Stanford Research Institute (SRI), was responsible for compiling a single file, HOSTS.TXT, which contained the names and addresses of every computer. Administrators would email SRI, which would then update the HOSTS.TXT file. Next, ARPANET users would download the new version of HOSTS.TXT using File Transfer Protocol (FTP). As the ARPANET grew, it became obvious that this approach wouldn't scale, for the following three key reasons: The bandwidth consumed in transmitting updated versions of an ARPANET-wide host file was proportional to the square of the number of hosts in the ARPANET. With the number of hosts growing at an exponential rate, the long-term impact was likely to be a load that no one host was going to be able to sustain. The static flat host file also meant that no two computers on the ARPANET could have the same name. As the number of hosts grew, the risk of adding a duplicate name grew, as did the difficulty of trying to control this centrally. The nature of the underlying network was changingthe large, timesharing computers that had once made up the ARPANET were being superseded by networks of workstationseach of which needed to have a unique host name. This would be difficult, if not impossible, to control centrally. As the ARPANET continued to grow, it became clear that ARPANET needed a better solution. Several proposals were generated based on the concept of a distributed naming service, which was based on a hierarchical name space. RFCs 882 and 883 emerged, which described the design for a domain name system, based on a distributed database containing generalized resource information. This design evolved, and RFCs 1034 and 1035 were issued to describe the Domain Name System (DNS) service used in today's Internet. This design continues to evolve, and a number of proposed updates and refinements are being discussed as this chapter is being written. What Is DNS? The DNS is an IETF-standard name service. The DNS service enables client computers on your network to register and resolve DNS domain names. These names are used to find and access resources offered by other computers on your network or other networks, such as the Internet. The following are the three main components of DNS: Domain name space and associated resource records (RRs) A distributed database of name-related information. DNS Name Servers Servers that hold the domain name space and RRs, and that answer queries from DNS clients. DNS Resolvers The facility within a DNS client that contacts DNS name servers and issues name queries to obtain resource record information.

Key DNS Terms

69

This section describes the key components of the DNS and defines key DNS terms. Domain Name Space The domain name space is a hierarchical, tree-structured name space, starting at an unnamed root used for all DNS operations. In the DNS name space, each node and leaf in the domain name space tree represents a named domain. Each domain can have additional child domains. Figure illustrates the structure of Internet domain name space.

Figure: Domain name space for the Internet. Domain Names Each node in the DNS tree, as Figure illustrates, has a separate name, referred to in RFC 1034 as a label. Each DNS label can be from 1 through 63 characters in length, with the root domain having a length of zero characters. A specific node's domain name is the list of the labels in the path from the node being named to the DNS Tree root. DNS convention is that the labels that compose a domain name are read left to rightfrom the most specific to the root (for example, www.kapoho.com). This full name is also known as the fully qualified domain name (FQDN). Domain names can be stored as upper case or lower case, but all domain comparisons and domain functions are defined, by RFC 1034, to be case insensitive. Thus, www.kapoho.com is identical to WWW.KAPOHO.COM for domain naming operations. Top-Level Domains A top-level domain is a DNS domain directly below the root. As the above mentioned figure illustrates, a number of top-level domains have been defined. Additional names (at least for the Internet) are difficult to create. The following are the three categories of toplevel domains:

"ARPA" This is a special domainused today for reverse-name lookups. 3-letter domains There are six 3-character, top-level domains noted below. 2-letter country-based domain names These country code domains are based on the International Organization for Standardization (ISO) country name, and are used principally by companies and organizations outside the US. The exception is 70

the UK, which uses .uk as the top-level domain, even though the ISO country code is GB. Table shows the six top-level domains in use today, as defined by RFC 1591. Table -Character Top-Level Domains in Use in the Internet 3-Character Domain Name Use Com Edu Gov Int Mil Net Commercial organizations, such as microsoft.com for the Microsoft Corporation Educational institutions, now mainly four-year colleges and universities, such as cmu.edu for Carnegie Mellon University Agencies of the US Federal Government, such as fbi.gov for the US Federal Bureau of Investigation Organizations established by international treaties, such as nato.int for NATO US military, such as af.mil for the US Air Force Computers of network providers, organizations dedicated to the Internet, Internet Service Providers (ISPs), and so forth, such as internic.net for the Internet Network Information Center (InterNIC) A top-level domain for groups that don't fit anywhere else, such as non-government or non-profit organizations (for example, reiki.org for information about Reiki)

Org

Note: While these are the only 3-letter domains available today, there is pressure to expand this number; we may well end up with more in the future. Resource Records (RR) A resource record is a record containing information relating to a domain that the DNS database can hold and that a DNS client can retrieve and use. For example, the host RR for a specific domain holds the IP address of that domain (host); a DNS client will use this RR to obtain the IP address for the domain. Each DNS server contains the RRs relating to those portions of the DNS namespace for which it's authoritative (or for which it can answer queries sent by a host). When a DNS server is authoritative for a portion of the DNS name space, those systems' administrators are responsible for ensuring that the information about that DNS name space portion is correct. To increase efficiency, a given DNS server can cache the RRs relating to a domain in any part of the domain tree. There are numerous RR types defined in RFCs 1035 and 1036, and in later RFCs. Most of the RR types are no longer needed or used.

71

Table lists the key RRs that might be used in a Windows 2000 network. (For more detail on the contents of specific RRs, see the "DNS Resource Records" section later in this chapter.) Table Key Resource Records as Used by a Windows 2000 Network Resource Record Type Contents Use A CNAME MX NS Host Address Used to hold a specific host's IP address. Can