You are on page 1of 172

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment-1 Date : 07.09.12

INTRODUCTION TO WIRESHARK
PROBLEM DEFINITION To familiarize about wireshark THEORETICAL BACKGROUND Wireshark is the basic tool for observing the messages exchanged between different protocols. It will also store and display the contents of various protocol fields in these captured messages. It is a computer application that analyzes network protocols by allowing users to interactively browse and capture traffic running on a computer network. It is compatible with a variety of operating systems, including Windows, OS X and Linux, and is used by security experts, network professionals and educators throughout the world.It is capable of capturing live packet from a network interface and also displays with a very detailed protocol information. The filtrations of packets can be done based the various criteria given by the user. The wireshark interface has mainly 5 components: a) Command menus: file and capture menu comes under this category. The file menu can be used to open, save, and close the interfaces. The capture menu allows the user to start capturing the packets. b) Packet listing window: displays a summary for each packet including packet number, the time of capture, address, protocol types, etc. c) Packet header details window: provides details about the packet selected in the packet listing window. d) Packet contents window: displays the entire content of the captured frame in both ASCII and hexadecimal format. e) Packet display filter field: we can filter the packets by providing corresponding protocol name in this field. CONCLUSION A familiarization of wireshark is done successfully.
University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 2 Date:07-09-2012

TRACING DNS WITH WIRESHARK


PROBLEM DEFINITION Experiment to Tracing DNS with Wireshark. Use http://www.ietf.org in browser for analysis. After performing Wireshark capturing, answer following questions. a) Locate the DNS query and response messages. Are they sent over UDP or TCP? b) What is the destination port for the DNS query message? What is the source port of DNS response message? c) Consider the subsequent TCP SYN packet sent by your host. Does the destination IP address of the SYN packet correspond to any of the IP addresses provided in the DNS response message?

THEORETICAL BACKGROUND Wire shark is a network packet analyzer. Gerald Combs was its founder. A network packet analyzer will try to capture network packets and tries to display that packet data as detailed as possible. A network packet analyzer as a measuring device used to examine what's going on inside a network cable, just like a voltmeter is used by an electrician to examine what's going on inside an electric cable. It is a computer application that analyzes network protocols by allowing users to interactively browse and capture traffic running on a computer network. Wireshark is compatible with a variety of operating systems, including Windows, OS X and Linux, and is used by security experts, network professionals and educators throughout the world. The following are some of the key features Wireshark provides: Capture live packet data from a network interface. Display packets with very detailed protocol information.

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Open and Save packet data captured. Import and Export packet data from and to a lot of other capture programs. Filter packets on many criteria. Search for packets on many criteria. Colorize packet display based on filters. Live capture and offline analysis Multi-platform: Runs on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD Captured network data can be browsed via a GUI, or via the TTY-mode TShark utility The most powerful display filters in the industry Rich VoIP analysis Create various statistics. Some intended purposes: Network administrators use it to troubleshoot network problems Network security engineers use it to examine security problems Developers use it to debug protocol implementations People use it to learn network protocol internals

DOMAIN NAME SYAYTEM(DNS) The Domain Name System protocol translates domain names into IP addresses. When a client wants to open a webpage at www.google.com, a query is sent to a DNS server (a.k.a. name server) to fetch the corresponding IP address. The IP returned by the name server is used to contact the Google web server the server that hosts the actual website contents. A client that wants to translate a name to an IP address sends a question to the name server(s) on its network. The name server provides an answer to the question, but it might have to contact several other servers to obtain the answer. A lot goes on behind the scenes that the client is blissfully unaware of.

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Usually, a client will know the IP address of one or more DNS servers after the DHCP boot process is completed. In order to resolve a hostname, a DNS query packet is sent. All DNS traffic between clients and name servers is encapsulated in UDP, and name servers always run on UDP port 53.

The DNS packet format

a) The first (0th)bit indicates query(0) or response(1) b) Next three bits (1-4) indicates Standard Query (0), Inverse Query (1) and Server Status Request (2). c) The 5th bit field indicates Authoritative answer. The name server is authoritative for the domain in the question section. d) The 6th bit field is set if message was truncated. With UDP this means that the total size of the reply exceeded 512 bytes and only the first 512 bytes of reply were returned. e) The 7th bit field indicates Recursion Desired. This bit can be set in a query and is
University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

returned in the response. f) The 8th bit field indicates Recursion Available or not. g) The next 3 bits (9-11) have to be 0. h) The next 4 bits (12-15) give a return code where 0 signifies No Error and 3 signifies name error.

DNS response A response sent by a name server to a client will contain the original questions in the Questions fields. Additionally the Resource Record fields contain one or more entries. A resource record entry has the following structure:

Name: Contains the object, domain or zone name that is the subject of the resource record.

Type: One of the available record types. Class: Again, this is normally 1 . TTL: Specifies the number of seconds that the record should be retained in the cache of the device reading the record.

RData Length: Indicates the size of the RData field, in bytes. Resource Data: The data portion of the resource record.

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROGRAM DEVELOPMENT Step 1: Start wireshark from the terminal. Step 2: select "Interfaces" from the Capture menu, Wireshark pops up the "Capture Interfaces" dialog box . As the "Capture Interfaces" dialog is showing live captured data, it is consuming a lot of system resources. Close this dialog as soon as possible to prevent excessive system load. Step 3: Start packet capture in Wireshark. Step 4: With your browser, visit the Web page: http://www.ietf.org Step 5: Stop packet capture.

SUMMARY OF RESULTS a).DNS query and response are send over UDP.

b) Destination port for the DNS query message is 53 the source port of DNS response message is 58180.

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

c) The destination IP address of the SYN packet correspond to source IP addresses provided
in the DNS response message

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

d) Yes, host issues new query.

CONCLUSION The program to trace DNS with wireshark is examined and corresponding results are noted along with screenshots.

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 3 Date: 07-09-2012

TRACING HTTP WITH WIRESHARK

PROBLEM DEFINITION Use http://www.ietf.org in browser for analysis. After performing Wireshark capturing, answer following questions.

a) Is your browser running HTTP version 1.0 or 1.1? What version of HTTP is the server running? b) What languages (if any) does your browser indicate that it can accept to the server? c) What is the IP address of server? d) What is the status code returned from the server to your browser? e) When the HTML file that you are retrieving was last modified at the server? f) How many bytes of content are being returned to your browser? g) By inspecting the raw data in the packet content window, do you see any headers within the data that are not displayed in the packet-listing window? If so, name one.

THEORETICAL BACKGROUND

HYPER TEXT TRANSFER PROTOCOL(HTTP) The Hypertext Transfer Protocol (HTTP) is an application-level protocol with the lightness and speed necessary for distributed, collaborative, hypermedia information systems. It is a generic, stateless, object-oriented protocol which can be used for many tasks, such as name servers and distributed object management systems, through extension of its request methods (commands). A feature of HTTP is the typing of data representation, allowing systems to be built independently of the data being transferred. HTTP has been in use by the World-Wide
University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Web global information initiative since 1990. The HTTP protocol is based on a request/response paradigm. A client establishes a connection with a server and sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content. The server responds with a status line, including the message's protocol version and a success or error code, followed by a MIMElike message containing server information, entity met information, and possible body content. HTTP commands are GET Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. HEAD Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content. POST Submits data to be processed to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both. PUT Uploads a representation of the specified resource. DELETE Deletes the specified resource. TRACE Echoes back the received request, so that a client can see what (if any) changes or additions have been made by intermediate servers. OPTIONS Returns the HTTP methods that the server supports for specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource. CONNECT Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate
University Register No:

10

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy.

PATCH Is used to apply partial modifications to a resource.

PROGRAM DEVELOPMENT Step 1: Start Wireshark from the terminal. Step 2: Select "Interfaces" from the Capture menu, Wireshark pops up the "Capture Interfaces" dialog box. As the "Capture Interfaces" dialog is showing live captured data, it is consuming a lot of system resources. Close this dialog as soon as possible to prevent excessive system load. Step 3: Start packet capture in Wireshark. Step 4: Use HTTP command Step 5: Stop packet capture.

University Register No:

11

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

SUMMARY OF RESULTS a) The browser is running on HTTP version 1.1.servr is also running on same version of HTTP.

b) 2. Browser indicate that it can accept eu_us ; en; q=0.5\r\n language to the server .

University Register No:

12

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

c) Server IP address is 64.170.98.30

d) 200 ok is the status code returned from the server to our browser.

University Register No:

13

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

e) HTML file that you are retrieving was last modified at the server on Thu ,30 august 2012 19:44:02 GMT\r\n .

f) content length is 561 bytes.

University Register No:

14

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

g) By inspecting the raw data in the packet content window, all headers within the data that are not displayed in the packet-listing window, no content missing. h) four

University Register No:

15

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

CONCLUSION The program to trace HTTP with wireshark is examined and corresponding results are noted along with screenshots.

University Register No:

16

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 4 Date: 07-09-2012

TRACING TCP WITH WIRESHARK

PROBLEM DEFINITION Experiment to Tracing TCP with Wireshark Create an ASCII text file and upload it to a server (192.168.0.189). After performing Wireshark capturing, answer following questions.

a)

What is the IP address and TCP port number used by the client computer (source) that is transferring the file to gaia.cs.umass.edu? To answer this question, its probably easiest to select an HTTP message and explore the details of the TCP packet used to carry this HTTP message, using the details of the selected packet header window

b)

What is the IP address of server? On what port number is it sending and receiving TCP segments for this connection?

c)

What is the IP address and TCP port number used by your client computer (source) to transfer the file to server?

d)

What is the sequence number of the TCP SYN segment that is used to initiate the TCP connection between the client computer and server? What is it in the segment that identifies the segment as a SYN segment?

e)

What is the sequence number of the SYNACK segment sent by server to the client computer in reply to the SYN? What is the value of the ACKnowledgement field in the SYNACK segment? How did server determine that value? What is it in the segment that identifies the segment as a SYNACK segment?

f)

What is the sequence number of the TCP segment containing the HTTP POST command? Note that in order to find the POST command, youll need to dig into the packet content field at the bottom of the Wireshark window, looking for a segment with a POST within its DATA field.

g)

Display TCP flow graph


17

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

h)

Display Time Sequence Graph

THEORETICAL BACKGROUND TCP is often described as a byte stream, connection-oriented, reliable delivery transport layer protocol.

Source Port A 16-bit number identifying the application the TCP segment originated from within the sending host. The port numbers are divided into three ranges, well-known ports (0 through 1023), registered ports (1024 through 49151) and private ports (49152 through 65535). Port assignments are used by TCP as an interface to the application layer. For example, the TELNET server is always assigned to the well-known port 23 by default on TCP hosts. A complete pair of IP addresses (source and destination) plus a complete pair of TCP ports (source and destination) define a single TCP connection that is globally unique. See [5] for further details. Destination Port A 16-bit number identifying the application the TCP segment is destined for on a receiving host. Destination ports use the same port number assignments as those set aside for source ports [5]. Sequence Number

University Register No:

18

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

A 32-bit number identifying the current position of the first data byte in the segment within the entire byte stream for the TCP connection. After reaching 232 -1, this number will wrap around to 0. Acknowledgement Number A 32-bit number identifying the next data byte the sender expects from the receiver. Therefore, the number will be one greater than the most recently received data byte. This field is only used when the ACK control bit is turned on (see below). Header Length A 4-bit field that specifies the total TCP header length in 32-bit words (or in multiples of 4 bytes if you prefer). Without options, a TCP header is always 20 bytes in length. The largest a TCP header may be is 60 bytes. This field is required because the size of the options field(s) cannot be determined in advance. Note that this field is called "data offset" in the official TCP standard, but header length is more commonly used. Reserved A 6-bit field currently unused and reserved for future use. Control Bits Urgent Pointer (URG). If this bit field is set, the receiving TCP should interpret the urgent pointer field (see below). Acknowledgement (ACK). If this bit field is set, the acknowledgement field described earlier is valid. Push Function (PSH). If this bit field is set, the receiver should deliver this segment to the receiving application as soon as possible. An example of its use may be to send a ControlBREAK request to an application, which can jump ahead of queued data. Reset the Connection (RST). If this bit is present, it signals the receiver that the sender is aborting the connection and all queued data and allocated buffers for the connection can be
University Register No:

19

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

freely relinquished. Synchronize (SYN). When present, this bit field signifies that sender is attempting to "synchronize" sequence numbers. This bit is used during the initial stages of connection establishment between a sender and receiver. No More Data from Sender (FIN). If set, this bit field tells the receiver that the sender has reached the end of its byte stream for the current TCP connection. Window A 16-bit integer used by TCP for flow control in the form of a data transmission window size. This number tells the sender how much data the receiver is willing to accept. The maximum value for this field would limit the window size to 65,535 bytes, however a "window scale" option can be used to make use of even larger windows. Checksum A TCP sender computes a value based on the contents of the TCP header and data fields. This 16-bit value will be compared with the value the receiver generates using the same computation. If the values match, the receiver can be very confident that the segment arrived intact. Three-Way Handshake

University Register No:

20

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROGRAM DEVELOPMENT Step 1: Start wireshark from the terminal. Step 2: select "Interfaces" from the Capture menu, Wireshark pops up the "Capture Interfaces" dialog box . As the "Capture Interfaces" dialog is showing live captured data, it is consuming a lot of system resources. Close this dialog as soon as possible to prevent excessive system load. Step 3: Start packet capture in Wireshark. Step 4: Upload a file to server using filezilla. Step 5: Monitor the packets and analyze them. Step 6:Stop packet capturing.

SUMMARY OF RESULTS a) IP Address of client: 192.168.31.1 TCP Port number of client: 42848

University Register No:

21

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

b) IP address of server: 192.168.0.189 Port number of server: 21

c) IP Address of client: 192.168.31.1 TCP Port number of client: 42838

University Register No:

22

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

d) Sequence number of the TCP SYN: 0

e) Sequence number of TCP SYNACK: 0 Acknowledgement: 1

University Register No:

23

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

f) Sequence number: 1

g) TCP flow graph

University Register No:

24

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

h) Display Time Sequence Graph

University Register No:

25

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

CONCLUSION The program to trace TCP with wireshark is examined and corresponding results are noted along with screenshots.

University Register No:

26

MITNE-107 Network Programming and Internet Lab Experiment No:5 Date: 07-09-2012

Department of information technology Rajagiri School of Engineering & Technology

TRACING IP AND ICMP WITH WIRESHARK


PROBLEM DEFINITION Use ping/ trace route command. After performing Wireshark capturing, answer following questions. a. What is the IP address of your computer embedded in ICMP packet. b. How many bytes are in the IP header? How many bytes are in the payload of the IP datagram? Explain how you determined the number of payload bytes. c. Has this IP datagram been fragmented? Explain how you determined whether or not the datagram has been fragmented. d. What is the value in the Identification field and the TTL field? e. Why is it that an ICMP packet does not have source and destination port numbers? f. Examine one of the ping request packets sent by your host. What are the ICMP type and code numbers? What other fields does this ICMP packet have? How many bytes are the checksum, sequence number and identifier fields? g. Examine the corresponding ping reply packet. What are the ICMP type and code numbers? What other fields does this ICMP packet have? How many bytes are the checksum, sequence number and identifier fields?

THEORETICAL BACKGROUND Internet Control Message Protocol (ICMP) The Internet Control Message Protocol (ICMP) protocol is classic example of a client server application. The ICMP server executes on all IP end system computers and all IP intermediate systems. The protocol is used to report problems with delivery of IP datagrams within an IP network. It can be sued to show when a particular End System (ES) is not responding, when an IP network is not reachable, when a node is overloaded, when an error occurs in the IP header information, etc. The protocol is also frequently used by Internet managers to verify correct operations of End Systems (ES) and to check that routers are
University Register No:

27

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

correctly routing packets to the specified destination address.

ICMP messages generated by router R1, in response to message sent by H0 to H1 and forwarded by R0. This message could, for instance be generated if the MTU of the link between R0 and R1 was smaller than size of the IP packet, and the packet had the Don't Fragment (DF) bit set in the IP packet header. The ICMP message is returned to H0, since this is the source address specified in the IP packet that suffered the problem. A modern version of Path MTU Discovery provides a mechanism to verify the Path MTU.

An ICMP message consisting of 4 bytes of PCI and an optional message payload. The format of an ICMP message is shown above. The 8-bit type code identifies the types of message. This is followed by at least the first 28 bytes of the packet that resulted in generation of the error message (i.e. the network-layer header and first 8 bytes of transport header). This payload is, for instance used by a sender that receives the ICMP message to perform Path MTU Discovery so that it may determine IP destination address of the packet that resulted in the error. Longer payloads are also encouraged (which can help better identify the reason why the ICMP message was generated and which program generated the original packet).The figure below shows the encapsulation of ICMP over an Ethernet LAN using an IP network layer header, and a MAC link layer header and trailer containing the 32-bit checksum:

University Register No:

28

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Encapsulation for a complete ICMP packet It is the responsibility of the network layer (IP) protocol to ensure that the ICMP message is sent to the correct destination. This is achieved by setting the destination address of the IP packet carrying the ICMP message. The source address is set to the address of the computer that generated the IP packet (carried in the IP source address field) and the IP protocol type is set to "ICMP" to indicate that the packet is to be handled by the remote end system's ICMP client interface. RFC792 specifies the Internet Control Message Protocol (ICMP) that is used with the Internet Protocol version 4 (IPv4). It defines, among other things, a number of error messages that can be used by an end-system and intermediate systems to report errors back to the sending system. The host requirements classifies ICMP these error messages into those that indicate "soft errors" (advising of problems), and those that indicate "hard errors" (which need to be responded to). A version of ICMP has also been defined for IPv6, called ICMPv6 . This subsumes all the equivalent functions of ICMP for IPv4 and adds other network-layer functions. ICMP error messages are up to 1280 bytes in size, and therefore always carry a substantial number of bytes from the packet that generated the error being reported.The Ping ApplicationThe "ping" program contains a client interface to ICMP. It may be used by a user to verify an end-to-end Internet Path is operational. The ping program also collects performance statistics (i.e. the measured round trip time and the number of times the remote server fails to reply. Each time an ICMP echo reply message is received, the ping program displays a single line of text. The text printed by ping shows the received sequence number, and the measured round trip time (in milliseconds). Each ICMP Echo message contains a sequence number (starting at 0) that is incremented after each transmission, and a timestamp value indicating the transmission time.

University Register No:

29

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Use of the ping program to test whether a particular computer ("sysa") is operational. The operation of ICMP is illustrated in the frame transition diagram shown above. In this case there is only one Intermediate System (IS). In this case two types of message are involved the ECHO request (sent by the client) and the ECHO reply (the response by the server). Each message may contain some optional data. When data are sent by a server, the server returns the data in the reply which is generated. ICMP packets are encapsulated in IP for transmission across an internet. Internet Protocol (IP) The Internet Protocol (IP) is a network-layer (Layer 3) protocol that contains addressing information and some control information that enables packets to be routed. IP is documented in RFC 791 and is the primary network-layer protocol in the Internet protocol suite. Along with the Transmission Control Protocol (TCP), IP represents the heart of the Internet protocols. IP has two primary responsibilities: providing connectionless, best-effort delivery of datagrams through an internetwork; and providing fragmentation and reassembly of datagrams to support data links with different maximum-transmission unit (MTU) sizes.

University Register No:

30

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

The following discussion describes the IP packet fields illustrated in Figure 30-2: VersionIndicates the version of IP currently used. IP Header Length (IHL)Indicates the datagram header length in 32-bit words. Type-of-ServiceSpecifies how an upper-layer protocol would like a current datagram to be handled, and assigns datagrams various levels of importance. Total LengthSpecifies the length, in bytes, of the entire IP packet, including the data and header. IdentificationContains an integer that identifies the current datagram. This field is used to help piece together datagram fragments. FlagsConsists of a 3-bit field of which the two low-order (least-significant) bits control fragmentation. The low-order bit specifies whether the packet can be fragmented. The middle bit specifies whether the packet is the last fragment in a series of fragmented packets. The third or high-order bit is not used. Fragment OffsetIndicates the position of the fragments data relative to the beginning of the data in the original datagram, which allows the destination IP process to properly reconstruct the original datagram. Time-to-LiveMaintains a counter that gradually decrements down to zero, at which point the datagram is discarded. This keeps packets from looping endlessly.
University Register No:

31

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

ProtocolIndicates which upper-layer protocol receives incoming packets after IP processing is complete. Header ChecksumHelps ensure IP header integrity. Source AddressSpecifies the sending node. Destination AddressSpecifies the receiving node. OptionsAllows IP to support various options, such as security. DataContains upper-layer information.

PROGRAM DEVELOPMENT Step 1: Start Wireshark from the terminal. Step 2: Select "Interfaces" from the Capture menu, Wireshark pops up the "Capture Interfaces" dialog box. As the "Capture Interfaces" dialog is showing live captured data, it is consuming a lot of system resources. Close this dialog as soon as possible to prevent excessive system load. Step 3: Start packet capture in wireshark. Step 4: Perform a ping operation to server. Step 5: In the wireshark window, under the ICMP protocol view the various details. Step 6: Stop the packet capture.

SUMMARY OF RESULTS a) Source: 192.168.31.1

University Register No:

32

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

a) ICMP

b) Header is 20 bytes.payload length is 84-20=64 That is total length- header length

University Register No:

33

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

c) No .fragment offset is 0.that means it is not fragmented.

University Register No:

34

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

d)

Identification field is oxoooo

TTL field is 64

e) ICMP is a session layer protocol(different than TCP or UDP) therefore it does not use port numbers.

University Register No:

35

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

f) When examining one of the Ping request sent by the host, we can see 6 fields. They are

a. Type b. Code c. Checksum d. Identifier e. Sequence Number f. Data

: 8 (Echo (ping) request) :0 : 0x114e [correct] : 0xfc31 : 8 (0x0008) : 56 bytes.

g) When examining one of the Ping reply packet, we can see 6 fields. They are

University Register No:

36

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

a. Type b. Code c. Checksum d. Identifier e. Sequence Number f. Data

: 0 (Echo (ping) reply) : 0 (0) : 0x194e [correct] : 0xfc31 : 8 (0x0008) : 56 bytes

CONCLUSION The program to trace IP and ICMP with wireshark is examined and corresponding results are noted along with screenshots.

University Register No:

37

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 6 Date:10-09-2012

TRACING ETHERNET WITH WIRESHARK

PROBLEM DEFINITION Use http://www.ietf.org in browser for analysis. After performing Wireshark capturing, answer following questions.

a) What is the 48-bit Ethernet address of your computer?

b) What is the 48-bit destination address in the Ethernet frame?

c) Give the hexadecimal value for the two-byte Frame type field. What do the bit(s) whose value is 1 mean within the flag field?

d) How many bytes from the very start of the Ethernet frame does the ASCII G in GET appear in the Ethernet frame?

THEORETICAL BACKGROUND Ethernet is a family of computer networking technologies for local area networks (LANs). Ethernet was commercially introduced in 1980 and standardized in 1985 as IEEE 802.3. Ethernet has largely replaced competing wired LAN technologies. The Ethernet standards comprise several wiring and signaling variants of the OSI physical layer in use with Ethernet. The original 10BASE5 Ethernet used coaxial cable as a shared medium. Later the coaxial cables were replaced by twisted pair and fiber optic links in conjunction with hubs or switches. Data rates were periodically increased from the original 10 megabits per second, to 100 gigabits per second.

University Register No:

38

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Systems communicating over Ethernet divide a stream of data into shorter pieces called frames. Each frame contains source and destination addresses and error-checking data so that damaged data can be detected and re-transmitted. As per the OSI model Ethernet provides services up to and including the data link layer.

University Register No:

39

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROGRAM DEVELOPMENT Step 1: Start Wireshark from the terminal.

Step 2: Select "Interfaces" from the Capture menu, Wireshark pops up the "Capture Interfaces" dialog box. As the "Capture Interfaces" dialog is showing live captured data, it is consuming a lot of system resources. Close this dialog as soon as possible to prevent excessive system load.

Step 3: Start packet capture in Wireshark.

Step 4: With your browser, visit the Web page: http://www.ietf.org

Step 5: Stop packet capture.

SUMMARY OF RESULTS a) 48 bit source address-18:a9:05:16:97:cf

University Register No:

40

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

b) 48 bit destination address-00:90:7f:8f:6c:a6

c) Hexa decimal vaulue is 0800

d)

Hexadecimal value of G is and it appears as 55th byte

University Register No:

41

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

e)

Hexadecimal value is 83b0

CONCLUSION The program to trace ETHERNET with wireshark is examined and corresponding results are noted along with screenshots.
University Register No:

42

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No:7 Date: 10-09-12

TRACING ARP WITH WIRESHARK

PROBLEM DEFINITION Use ARP command. After performing Wireshark capturing, answer following questions.

a. What are the hexadecimal values for the source and destination addresses in the Ethernet frame containing the ARP request message?

b. Where in the ARP request does the question appear the Ethernet address of the machine whose corresponding IP address is being queried?

c. Where in the ARP message does the answer to the earlier ARP request appear the IP address of the machine having the Ethernet address whose corresponding IP address is being queried?

THEORETICAL BACKGROUND

Address Resolution Protocol (ARP) The address resolution protocol (ARP) is a protocol used by the Internet Protocol (IP) , specifically IPv4, to map IP network addresses to the hardware addresses used by a data link protocol. The protocol operates below the network layer as a part of the interface between the OSI network and OSI link layer. It is used when IPv4 is used over Ethernet.

University Register No:

43

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

The term address resolution refers to the process of finding an address of a computer in a network. The address is "resolved" using a protocol in which a piece of information is sent by a client process executing on the local computer to a server process executing on a remote computer. The information received by the server allows the server to uniquely identify the network system for which the address was required and therefore to provide the required address. The address resolution procedure is completed when the client receives a response from the server containing the required address. An Ethernet network uses two hardware addresses which identify the source and destination of each frame sent by the Ethernet. The destination address (all 1's) may also identify a broadcast packet (to be sent to all connected computers). The hardware address is also known as the Medium Access Control (MAC) address, in reference to the standards which define Ethernet. Each computer network interface card is allocated a globally unique 6 byte link address when the factory manufactures the card (stored in a PROM). This is the normal link source address used by an interface. A computer sends all packets which it creates with its own hardware source link address, and receives all packets which match the same hardware address in the destination field or one (or more) pre-selected broadcast/multicast addresses. The Ethernet address is a link layer address and is dependent on the interface card which is used. IP operates at the network layer and is not concerned with the link addresses of individual nodes which are to be used.The address resolution protocol (ARP) is therefore used to translate between the two types of address. The ARP client and server processes operate on all computers using IP over Ethernet. The processes are normally implemented as part of the software driver that drives the network interface card. There are four types of ARP messages that may be sent by the ARP protocol. These are identified by four values in the "operation" field of an ARP message. The types of message are: 1. ARP request 2. ARP reply 3. RARP request 4. RARP reply

University Register No:

44

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

The format of an arp message is shown below:

Format of an ARP message used to resolve the remote MAC Hardware Address To reduce the number of address resolution requests, a client normally caches resolved addresses for a (short) period of time. The ARP cache is of a finite size, and would become full of incomplete and obsolete entries for computers that are not in use if it was allowed to grow without check. The ARP cache is therefore periodically flushed of all entries. This deletes unused entries and frees space in the cache. It also removes any unsuccessful attempts to contact computers which are not currently running. If a host changes the MAC address it is using, this can be detected by other hosts when the cache entry is deleted and a fresh ARP message is sent to establish the new association. The use of gratuitous ARP (e.g. triggered when the new NIC interface is enabled with an IP address) provides a more rapid update of this information. Example of use of the Address Resolution Protocol (ARP) The figure below shows the use of ARP when a computer tries to contact a remote computer on the same LAN (known as "sysa") using the "ping" program. It is assumed that no previous IP datagrams have been received from this computer, and therefore ARP must first be used to identify the MAC address of the remote computer.

The ARP request message ("who is X.X.X.X tell Y.Y.Y.Y", where X.X.X.X and Y.Y.Y.Y
University Register No:

45

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

are IP addresses) is sent using the Ethernet broadcast address, and an Ethernet protocol type of value 0x806. Since it is broadcast, it is received by all systems in the same collision domain (LAN). This is ensures that is the target of the query is connected to the network, it will receive a copy of the query. Only this system responds. The other systems discard the packet silently. The target system forms an arp response ("X.X.X.X is hh:hh:hh:hh:hh:hh", where hh:hh:hh:hh:hh:hh is the Ethernet source address of the computer with the IP address of X.X.X.X). This packet is unicast to the address of the computer sending the query (in this case Y.Y.Y.Y). Since the original request also included the hardware address (Ethernet source address) of the requesting computer, this is already known, and doesn't require another ARP message to find this out.

Gratuitous ARP Gratuitous ARP is used when a node (end system) has selected an IP address and then wishes to defend its chosen address on the local area network (i.e. to check no other node is using the same IP address). It can also be used to force a common view of the node's IP address (e.g. after the IP address has changed).

University Register No:

46

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Use of this is common when an interface is first configured, as the node attempts to clear out any stale caches that might be present on other hosts. The node simply sends an arp request for itself. Proxy ARP Proxy ARP is the name given when a node responds to an arp request on behalf of another node. This is commonly used to redirect traffic sent to one IP address to another system. Proxy ARP can also be used to subvert traffic away from the intended recipient. By responding instead of the intended recipient, a node can pretend to be a different node in a network, and therefore force traffic directed to the node to be redirected to itself. The node can then view the traffic (e.g. before forwarding this to the originally intended node) or could modify the traffic. Improper use of Proxy ARP is therefore a significant security vulnerability and some networks therefore implement systems to detect this. Gratuitous ARP can also help defend the correct IP to MAC bindings.

PROGRAM DEVELOPMENT Step 1: Start Wireshark from the terminal. Step 2: Select "Interfaces" from the Capture menu, Wireshark pops up the "Capture Interfaces" dialog box. As the "Capture Interfaces" dialog is showing live captured data, it is consuming a lot of system resources. Close this dialog as soon as possible to prevent excessive system load. Step 3: Start packet capture in Wireshark. Step 4: Use ARP command Step 5: Stop packet capture.

SUMMARY OF RESULTS a).The hexadecimal values for the source and destination addresses in the Ethernet frame containing the ARP request message are: Hexadecimal value for Source Address: 00 1b fc 28 78 66

University Register No:

47

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Hexadecimal value for Destination Address: ff ff ff ff ff ff

b. The question is shown in the screenshot given below:

University Register No:

48

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

c.

CONCLUSION The program to trace ARP with wireshark is examined and corresponding results are noted along with screenshots.
University Register No:

49

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Network/ Server Configuration

University Register No:

50

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 1 Date:8-10-2012 LINUX SYSTEM MANAGEMENT BASICS PROBLEM DEFINITION 1.Customizing User Environment 2.Linux Network Management Basics

THEORETICAL BACKGROUND 1. PING Ping used to check if there is a network connection to another computer. When a web browser fails to connect to a web site on the Internet or LAN (local area network) the cause is often the web server, which may be down or overloaded, or it may be a network failure that prevents the connection to the other machine. Therefore the first step in diagnosing the problem is to test if the network connection is working. The ping command does that without requiring a web server. In a shell window you simply type "ping" followed by the URL or IP address of the computer you want to test. Your computer will respond with a summary of the results of each attempt to contact that computer. Syntax ping [options]host We can use different options as follows: -a Make ping audible. Beep each time response is received. -b Ping a broadcast address. -c count Stop after sending count ECHO_REQUEST packets. With deadline option, ping waits for count ECHO_REPLY packets, until the timeout expires. -n Show network addresses as numbers. ping normally displays addresses as host names. -q Quiet outputnothing is displayed except the summary lines at startup time and when
University Register No:

51

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

finished. -i Specify the interval between successive transmissions. The default is one second. -t Set the IP Time to Live to n seconds. -w Exit ping after n seconds. Steps Open a terminal window. Type ping in the command window. Hit the space bar once. Type the ip or website address that you want to ping. Hit enter.

If the website is up and actively responding, you receive replies back from the server that you pinged with the following information: The IP address The number of Bytes sent The time it took in milliseconds The TTL is Time to Live (This indicated the number of "hops" back from the computer pinged from that computers initial TTL value.) Press CTRL C to stop the command and show results Example: Ping www.google.com ping 74.125.67.100 These commands send a bit of data (i.e. an ICMP packet) to the remote host, and wait for a response. If the system is able to make a connection, for every packet it will report on the "round trip time." Here is the output of four pings of google.com: 64 bytes from yx-in-f100.1e100.net (74.125.45.100): icmp_seq=1 ttl=50 time=33.8 ms
University Register No:

52

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

64 bytes from yx-in-f100.1e100.net (74.125.45.100): icmp_seq=2 ttl=50 time=53.2 ms 64 bytes from yx-in-f100.1e100.net (74.125.45.100): icmp_seq=3 ttl=50 time=35.9 ms 64 bytes from yx-in-f100.1e100.net (74.125.45.100): icmp_seq=4 ttl=50 time=37.5 ms In this case yx-in-f100.1e100.net is the reverse DNS for this IP address. The time field specifies in milliseconds that the round trip takes for an individual packet. When you've gathered the amount of information you need, send Control+C to interrupt the process. At this juncture, you'll be presented with some statistics. -This will resemble: --- google.com ping statistics --4 packets transmitted, 4 received, 0% packet loss, time 3007ms rtt min/avg/max/mdev = 33.890/40.175/53.280/7.679 ms There are several important data points to notice. They are: -Packet Loss, or the discrepancy between the number of packets sent and the number of packets that return successfully. -Round Trip Time statistics on the final line report important information about all the ping responses. For this ping we see that the fastest packet round trip took 33.89 milliseconds. The longest packet took 53.28 milliseconds. The average round trip took 40.175 milliseconds. A single standard deviation unit for these four packets is 7.67 milliseconds. -The lower the round trip number in milliseconds, the better. The higher the round trip number in milliseconds, the higher the latency, which may indicate a network problem between your computer and the server you pinged.

2. TRACEROUTE The traceroute command expands on the functionality of the ping command. traceroute provides a report on the path that the packets take to get from the local machine to the remote machine. Route information is useful when troubleshooting a networking issue.Traceroute utility uses the TTL field in the IP header to achieve its operation. This field is usually set to 32 or 64. Each time the packet is held on an intermediate router, it decreases the TTL value by 1. When a router finds the TTL value of 1 in a received packet then that packet is not forwarded but instead discarded.After discarding the packet, router sends an ICMP error message of Time exceeded back to the source from where packet generated. The ICMP packet that is sent back contains the IP address of the router.So now it can be easily understood that traceroute operates by sending packets with TTL value starting from 1 and
University Register No:

53

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

then incrementing by one each time. Each time a router receives the packet, it checks the TTL field, if TTL field is 1 then it discards the packet and sends the ICMP error packet containing its IP address and this is what traceroute requires. So traceroute incrementally fetches the IP of all the routers between the source and the destination. 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. -v 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. -x Prevent traceroute from calculating checksums. Note that checksums are usually required for the last hop when using ICMP ECHO probes. See the -I option. -f first_ttl 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. -g gateway 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.

University Register No:

54

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

-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 send probes to a local host through an interface that has been dropped by the router daemon.

-i iface

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.

-m max_ttl

Set the maximum ttl used in outgoing probe packets. The default is 30 hops, which is the same default used for TCP connections.

-p port

Set the base UDP port number used in probes. The default is 33434. traceroute hopes that nothing is listening on UDP ports

(base+(nhop1)*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. -q nqueries -s src_addr 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. -t tos 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.
University Register No:

55

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

-w waittime

Set the time, in seconds, to wait for a response to a probe. The default is five (5) seconds.

Host

The network host.

Here is an example of output from a traceroute command: traceroute to google.com (74.125.53.100), 30 hops max, 40 byte packets 1 207.192.75.2 (207.192.75.2) 0.414 ms 0.428 ms 0.509 ms 2 vlan804.tbr2.mmu.nac.net (209.123.10.13) 0.287 ms 0.324 ms 0.397 ms 3 0.e1-1.tbr2.tl9.nac.net (209.123.10.78) 1.331 ms 1.402 ms 1.477 ms 4 core1-0-2-0.lga.net.google.com (198.32.160.130) 1.514 ms 1.497 ms 1.519 ms 5 209.85.255.68 (209.85.255.68) 1.702 ms 72.14.238.232 (72.14.238.232) 1.731 ms

21.031 ms 6 209.85.251.233 (209.85.251.233) 26.111 ms 216.239.46.14 (216.239.46.14) 23.582 ms 23.468 ms 7 216.239.43.80 (216.239.43.80) 123.668 ms 209.85.249.19 (209.85.249.19) 47.228 ms 47.250 ms 8 209.85.241.211 (209.85.241.211) 76.733 ms 216.239.43.80 (216.239.43.80) 73.582 ms 73.570 ms 9 209.85.250.144 (209.85.250.144) 86.025 ms 86.151 ms 86.136 ms 10 64.233.174.131 (64.233.174.131) 80.877 ms 216.239.48.34 (216.239.48.34) 76.212 ms 64.233.174.131 (64.233.174.131) 80.884 ms 12 216.239.48.32 (216.239.48.32) 81.267 ms 81.198 ms 81.186 ms 12 216.239.48.137 (216.239.48.137) 77.478 ms pw-in-f100.1e100.net (74.125.53.100) 79.009 ms 216.239.48.137 (216.239.48.137) 77.437 ms Often the hostnames and IP addresses on either side of a failed jump are useful in determining who operates the machine where the routing error occurs. Failed jumps are designated by line with three asterisks (e.g. * * *).

3. NETSTAT: In computing, netstat (network statistics) is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface
University Register No:

56

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

(network interface controller or software-defined network interface) and network protocol statistics. It is available on Unix, Unix-like, and Windows NT-based operating systems.It is used for finding problems in the network and to determine the amount of traffic on the network as a performance measurement.Different parameters used with this are as follows: Nestat a: All active connections and TCP and UDP ports on which the computer is listening. Netstat e: Shows the Ethernet statistics. Netstat m: Displays the memory statistics for the networking code. Netstat s: Displays the statistics of the protocol. Netstat h: Displays the help command window.

Netstat provides statistics for the following:

Proto - The name of the protocol (TCP or UDP). Local Address - The IP address of the local computer and the port number being used. The name of the local computer that corresponds to the IP address and the name of the port is shown unless the -n parameter is specified. If the port is not yet established, the port number is shown as an asterisk (*).

Foreign Address - The IP address and port number of the remote computer to which the socket is connected. The names that corresponds to the IP address and the port are shown unless the -n parameter is specified. If the port is not yet established, the port number is shown as an asterisk (*).

State - Indicates the state of a TCP connection. The possible states are as follows: CLOSE_WAIT, CLOSED, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2,

LAST_ACK, LISTEN, SYN_RECEIVED, SYN_SEND, and TIME_WAIT. Examples:

University Register No:

57

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

To display the statistics for only the TCP or UDP protocols, type one of the following commands:
netstat -sp tcp netstat -sp udp

4. /ETC FOLDER: This is the configuration file for the linux system.In linux the directories and files are arranged in a tree structure./represents the root of the tree.Most of the /etc files are text files. The /etc maintains a lot of files. Some of them are described below. /etc/passwd The user database, with fields giving the username, real name, home directory, and other information about each user. The format is documented in the passwd manual page. /etc/shadow /etc/shadow is an encrypted file the holds user passwords. /etc/fdprm Floppy disk parameter table. Describes what different floppy disk formats look like. Used by setfdprm . See the setfdprm manual page for more information. /etc/fstab Lists the filesystems mounted automatically at startup by the mount -a command (in /etc/rc or equivalent startup file). Under Linux, also contains information about swap areas used automatically by swapon -a .

University Register No:

58

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

/etc/group Similar to /etc/passwd, but describes groups instead of users. See the group manual page in section 5 for more information. /etc/inittab Configuration file for init. /etc/issue Output by getty before the login prompt. Usually contains a short description or welcoming message to the system. The contents are up to the system administrator. /etc/magic The configuration file for file. Contains the descriptions of various file formats based on which file guesses the type of the file. See the magic and file manual pages for more information. /etc/motd The message of the day, automatically output after a successful login. Contents are up to the system administrator. Often used for getting information to every user, such as warnings about planned downtimes. /etc/mtab List of currently mounted filesystems. Initially set up by the bootup scripts, and updated automatically by the mount command. Used when a list of mounted filesystems is needed, e.g., by the df command.

5. ARP Address Resolution Protocol (ARP) is a telecommunications protocol used for resolution of
University Register No:

59

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

network layer addresses into link layer addresses, a critical function in multiple-access networks. ARP was defined by RFC 826 in 1982. It is Internet Standard STD 37. It is also the name of the program for manipulating these addresses in most operating systems.ARP manipulates the kernel's ARP cache in various ways. The primary options are clearing an address mapping entry and manually setting up one. For debugging purposes, the ARP program also allows a complete dump of the ARP cache. Syntax: arp [-evn] [-H type] [-i if] -a [hostname]

arp [-v] [-i if] -d hostname [pub] arp [-v] [-H type] [-i if] -s hostname hw_addr [temp] arp [-v] [-H type] [-i if] -s hostname hw_addr [netmask nm] pub arp [-v] [-H type] [-i if] -Ds hostname ifa [netmask nm] pub arp [-vnD] [-H type] [-i if] -f [filename] Options: -v, --verbose Tell the user what is going on by being verbose.

-n, --numeric Shows numerical addresses instead of trying to determine symbolic host, port or user names.

-H type, --hw-type type, -t type When setting or reading the ARP cache, this optional parameter tells arp which class of entries it should check for. The default value of this parameter is ether (i.e. hardware code 0x01 for IEEE 802.3 10Mbps Ethernet). Other values might include network technologies such as ARCnet (arcnet) , PROnet (pronet) , AX.25 (ax25) and NET/ROM (netrom).

University Register No:

60

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

-a [hostname], --display [hostname] Shows the entries of the specified hosts. If the hostname parameter is not used, all entries will be displayed. The entries will be displayed in alternate (BSD) style.

-d hostname, --delete hostname Remove any entry for the specified host. This can be used if the indicated host is brought down, for example.

-D, --use-device Use the interface ifa's hardware address.

-e Shows the entries in default (Linux) style. -i If, --device If Select an interface. When dumping the ARP cache only entries matching the specified interface will be printed. When setting a permanent or temp. ARP entry this interface will be associated with the entry; if this option is not used, the kernel will guess based on the routing table. For pub entries the specified interface is the interface on which ARP requests will be answered.

-s hostname hw_addr, --set hostname Manually create an ARP address mapping entry for host hostname with hardware address set to hw_addr class, but for most classes one can assume that the usual presentation can be used. For the Ethernet class, this is 6 bytes in hexadecimal, separated by colons. When adding proxy arp entries (that is those with the publish flag set a netmask may be specified to proxy arp for entire subnets. This is not good practice, but is supported by older kernels because it can be useful. If the temp flag is not supplied entries will be permanent stored into the ARP cache.

-f filename, --file filename Similar to the -s option, only this time the address info is taken from file filename set up. The name of the data file is very often /etc/ethers, but this is not official. If no filename is specified /etc/ethers is used as default.
University Register No:

61

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

The format of the file is simple; it only contains ASCII text lines with a hostname, and a hardware address separated by whitespace. Additionally the pub, temp and netmask flags can be used. 6. ROUTE Route command by default will show the details of the kernel routing table entries. In this example, the ip-address of the system where the route command is being executed is 192.168.1.157 $ route Kernel IP routing table Destination 192.168.1.0 Gateway * Genmask 255.255.255.0 U Flags Metric Ref 0 0 Use Iface

0 eth0

The above command shows that if the destination is within the network range 192.168.1.0 192.168.1.255, then the gateway is *, which is 0.0.0.0. When packets are sent within this IP range, then the MAC address of the destination is found through ARP Protocol and the packet will be sent to the MAC address.

7. SETTING THE HOSTNAME:

One can change the hostname of the system using the following steps: 1. Set the hosts and hostname to the home/ubuntu folder. 2. Replace the hostname ubuntu to the desired hostname by editing profile sudo gedit /home/ubuntu/.profile

3. Sudo cp /home/ubuntu/hostname /etc 4. Sudo cp /home/ubuntu/hosts /etc

University Register No:

62

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

8.IP ADDRESSING An IP (Internet Protocol) address is a unique identifier for a node or host connection on an IP network. An IP address is a 32 bit binary number usually represented as 4 decimal values, each representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points. This is known as "dotted decimal" notation. Example: 140.179.220.200 It is sometimes useful to view the values in their binary form. 140 .179 .220 .200 10001100.10110011.11011100.11001000 Every IP address consists of two parts, one identifying the network and one identifying the node. The Class of the address and the subnet mask determine which part belongs to the network address and which part belongs to the node address. Address Classes There are 5 different address classes. You can determine which class any IP address is in by examining the first 4 bits of the IP address. Class A addresses begin with 0xxx, or 1 to 126 decimal. Class B addresses begin with 10xx, or 128 to 191 decimal. Class C addresses begin with 110x, or 192 to 223 decimal. Class D addresses begin with 1110, or 224 to 239 decimal. Class E addresses begin with 1111, or 240 to 254 decimal. Addresses beginning with 01111111, or 127 decimal, are reserved for loopback and for internal testing on a local machine.Class D addresses are reserved for multicasting. Class E addresses are reserved for future use. They should not be used for host addresses. Now we can see how the Class determines, by default, which part of the IP address belongs to the network (N) and which part belongs to the node (n). Class A -- NNNNNNNN.nnnnnnnn.nnnnnnn.nnnnnnn Class B -- NNNNNNNN.NNNNNNNN.nnnnnnnn.nnnnnnnn Class C -- NNNNNNNN.NNNNNNNN.NNNNNNNN.nnnnnnnn In the example, 140.179.220.200 is a Class B address so by default the Network part of the address (also known as the Network Address) is defined by the first two octets (140.179.x.x) and the node part is defined by the last 2 octets (x.x.220.200). In order to specify the network address for a given IP address, the node section is set to all
University Register No:

63

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

"0"s. In example, 140.179.0.0 specifies the network address for 140.179.220.200. When the node section is set to all "1"s, it specifies a broadcast that is sent to all hosts on the network. 140.179.255.255 specifies the example broadcast address. Note that this is true regardless of the length of the node section.

9.SUBNETTING Subnetting an IP Network can be done for a variety of reasons, including organization, use of different physical media (such as Ethernet, FDDI, WAN, etc.), preservation of address space, and security. The most common reason is to control network traffic. In an Ethernet network, all nodes on a segment see all the packets transmitted by all the other nodes on that segment. Performance can be adversely affected under heavy traffic loads, due to collisions and the resulting retransmissions. A router is used to connect 000000IP networks to minimize the

amount of traffic each segment must receive. Applying a subnet mask to an IP address allows you to identify the network and node parts of the address. Performing a bitwise logical AND operation between the IP address and the subnet mask results in the Network Address or Number. For example, using our test IP address and the default Class B subnet mask, we get:

10001100.10110011.11110000.11001000 140.179.240.200 Class B IP Address 11111111.11111111.00000000.00000000 255.255.000.000 Default Class B Subnet Mask

10001100.10110011.00000000.00000000 140.179.000.000 Network Address Default subnet masks: Class A - 255.0.0.0 - 11111111.00000000.00000000.00000000 Class B - 255.255.0.0 - 11111111.11111111.00000000.00000000 Class C - 255.255.255.0 - 11111111.11111111.11111111.00000000

More restrictive subnet masks Additional bits can be added to the default subnet mask for a given Class to further subnet, or breakdown, a network. When a bitwise logical AND operation is performed between the subnet mask and IP address, the result defines the Subnet Address. There are some
University Register No:

64

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

restrictions on the subnet address. Node addresses of all "0"s and all "1"s are reserved for specifying the local network (when a host does not know it's network address) and all hosts on the network (broadcast address), respectively. This also applies to subnets. A subnet address cannot be all "0"s or all "1"s. This also implies that a 1 bit subnet mask is not allowed. This restriction is required because older standards enforced this restriction. Recent standards that allow use of these subnets have superceded these standards, but many "legacy" devices do not support the newer standards. If you are operating in a controlled environment, such as a lab, you can safely use these restricted subnets.To calculate the number of subnets or nodes, use the formula (2^n - 2) where n = number of bits in either field. Multiplying the number of subnets by the number of nodes available per subnet gives you the total number of nodes available for your class and subnet mask. Also, note that although subnet masks with non-contiguous mask bits are allowed they are not recommended. Example: 10001100.10110011.11011100.11001000 140.179.220.200 IP Address 11111111.11111111.11100000.00000000 255.255.224.000 Subnet Mask

10001100.10110011.11000000.00000000 140.179.192.000 Subnet Address 10001100.10110011.11011111.11111111 140.179.223.255 Broadcast Address In this example a 3 bit subnet mask was used. There are 6 subnets available with this size mask (remember that subnets with all 0's and all 1's are not allowed). Each subnet has 8190 nodes. Each subnet can have nodes assigned to any address between the Subnet address and the Broadcast address. This gives a total of 49,140 nodes for the entire class B address subnetted this way. Notice that this is less than the 65,534 nodes an unsubnetted class B address would have. Subnetting always reduces the number of possible nodes for a given network. There are complete subnet tables available here for Class A, Class B and Class C. These tables list all the possible subnet masks for each class, along with calculations of the number of networks, nodes and total hosts for each subnet. Subnetting Procedure: An example.

There is a class B address. We require 6 subnets. Default subnet mask for Class B address: 255.255.0.0.

University Register No:

65

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Step One: Defining Subnet Mask

We now follow the following steps to define the subnet mask: a) We have determined the number of physical segments in our network (six). Convert this number to binary format: 110. b) Count the number of bits required to represent the number of physical segments in binary. Representing six in binary requires three bits. c) We need to borrow these three bits from the host id section of the IP addresses. d) Convert the required number of bits to decimal format in high order (from left to right) in the third octet of the default subnet mask. For example, in this case, three bits are required; therefore, configure the first three bits of the host ID (third octet of the IP address) as the subnet ID. Our third octet of subnet mask is 1110000. The decimal value for this is 224. Therefore the subnet mask for this class B address is: 255.255.224.0

Step two: Defining Subnet IDs. e) List the number of bits in high order used for the subnet ID. In this case 3 bits are to represent the subnet mask, the binary octet is 11100000. f) Raise 2 to the power of the bit, and then subtract 2 to determine the possible bit

combinations. Why subtract 2? Because we cannot have all 0s and all 1s subnets. g) Convert the bit with the lowest value to decimal format. In this case we have 11100000. The lowest value is 32. h) Starting with zero, increment the value of each bit combination until the next increment is 256. i) Defining subnet numbers

In general, there are eight subnets (two invalid). They will be numbered 0 through 7. In other words, if we have to define subnet #n, we need to place the binary representation of n into the bits of the subnet-number field. For example, to define subnet #6, simply place the binary representation of 6 (110) into the 3-bits of the subnet-number field.

Subnet 0: x.y.0.0 (All 0s not possible) Subnet 1: x.y.32.0 Subnet 2: x.y.64.0 Subnet 3: x.y.96.0
66

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Subnet 4: x.y.128.0 Subnet 5: x.y.160.0 Subnet 6: x.y.192.0 Subnet 7: x.y.224.0 (All is not possible)

CONCLUSION The basic functions and commands of networking in linux based systems have been studied. Also mentioned familiarization experiments were successfully completed.

University Register No:

67

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 2 Date: 15-10-2012

IMPLEMENTATION OF APACHE WEBSERVER

PROBLEM DEFINITION Implement Apache web server

THEORETICAL BACKGROUND Web server Web server is software that helps to deliver Web content that can be accessed through the Internet. The most common use of web servers is to host websites, but there are other uses such as gaming, data storage or running enterprise applications. The primary function of web server is to deliver web pages on the request to clients using the Hypertext Transfer Protocol (HTTP). This means delivery of HTML documents and any additional content that may be included by a document, such as images, style sheets and scripts. Apache The Apache HTTP Server commonly referred to as Apache, is a web server software notable for playing a key role in the initial growth of the World Wide Web. Apache is developed and maintained by an open community of developers under apache Software Foundation. The application is available for a wide variety of operating systems, including Unix, Linux, Solaris, Microsoft Windows. Released under the Apache License, Apache is open-source software. Apache has been the most popular HTTP server software in use. As of September 2012 Apache was estimated to serve 54.98% of all active websites and 58.49% of the top servers across all domains. Apache is designed to work over a network, so Apache and the applications that talk to it dont have to be on the same computer. These applications are generically known as clients. Of course, a network can be defined as anything from a local intranet to the whole Internet, depending on the servers purpose and target audience. The most common kind of client is of
University Register No:

68

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

course a Web browser. The main task of a Web server is to translate a request into a response suitable for the circumstances at the time. When the client opens communication with Apache, it sends Apache a request for a resource. Apache either provides that resource or provides an alternative response to explain why the request couldnt be fulfilled. In many cases, the resource is a Hypertext Markup Language (HTML) Web page residing on a local disk, but this is only the simplest option. It can be many other things, tooan image file, the result of a script that generates HTML output, a Java applet thats downloaded and run by the client, and so on. Apache uses HTTP to talk with clients. Its a request/response protocol, which means that it defines how clients make requests and how servers respond to them: Every HTTP communication starts with a request and ends with a response. The Apache executable takes its name from the protocol, and on Unix systems is generally called httpd, short for HTTP daemon, In Unix terminology, applications that provide services rather than directly communicate with users are called daemons. PROGRAM DEVELOPMENT Step 1: Access root privilege using sudo -s Step 2: Download the latest stable version of apache and unzip it using the command tar xvf httpd-2_0_NN.tar or gunzip -d httpd-2_0_NN.tar.gz This creates a new directory under the current directory with the source files. Step 3:Once the files are obtained configure the source file ./configure Step 4: As with any source installation building the installation is required make make install Step 5: Assuming that there were no problems, you are ready to customize your Apache configuration. This really just amounts to editing the httpd.conf file. This file is
University Register No:

69

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

located in the /usr/local/apache2/conf

Step 6: Start the apache server using the following command apachectl start Step 7: Open a web browser on the same machine and type http://localhost/ in the

address box. If the page that appears have the message It Works! that means the server is running. While installing apache the system may prompt for the installation of other packages such as apr, apr-util and pcre. For this we follow the same steps from step 1 to step 4.

CONCLUSION Apache web server was installed; Mentioned familiarization experiments were successfully completed.

University Register No:

70

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 03 Date: 22-10-2012

IMPLEMENTATION OF FTP SERVER

PROBLEM DEFINITION Implement the FTP Server and familiarize its functionality.

THEORETICAL BACKGROUND File Transfer Protocol (FTP) operates on the application layer of the OSI model, and is used to transfer files using TCP/IP. To do so, an FTP server has to be running and waiting for incoming requests. The client computer is then able to communicate with the server on port 21. This connection, called the control connection, remains open for the duration of the session. A second connection, called the data connection, can either be opened by the server from its port 20 to a negotiated client port (active mode), or by the client from an arbitrary port to a negotiated server port (passive mode) as required to transfer file data. The control connection is used for session administration, for example commands, identification and passwords exchanged between the client and the server. To transfer files with FTP, you use a program often called the "client." The FTP client program initiates a connection to a remote computer running FTP "server" software. After the connection is established, the client can choose to send and/or receive copies of files, singly or in groups. To connect to an FTP server, a client requires a username and password as set by the administrator of the server. Many public FTP archives follow a special convention for that accepts a username of "anonymous." FTP may run in active or passive mode, which determines how the data connection is established. In active mode, the client creates a TCP control connection to the server and sends the server the client's IP address and an arbitrary client port number, and then waits until the server initiates the data connection over TCP to that client IP address and
University Register No:

71

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

client port number. In situations where the client is behind a firewall and unable to accept incoming TCP connections, passive mode may be used. In this mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection from an arbitrary client port to the server IP address and server port number received.

PROGRAM DEVELOPMENT 1. Sudo apt-get install apache2 2. Using synaptic package install gadmin-proftpd basic. 3. Check its working using commands 1. sudo /etc/inti.d/apache2 start 2. sudo /etc/init.d/proftpd start 3. sudo /etc/init.d/proftpd stop 4. sudo /etc/init.d/apache2 stop

Configurations 4. Create a folder in /var/www/ Eg: /var/www/web Its the folder assigned for the user 5. Execute command : cd /etc/apache2/sites-available Edit file default and save as website name. Eg: ann.rset Edit file default at 3 places 1. ServerName ann.rset (this line is added after ServerDomain line)

2. Document root /var/www/web 3. Directory </var/www/web/> 6. Create an index.html in web 7. Edit hosts file Sudo gedit /etc/hosts
University Register No:

72

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Add the 3rd line: Ipaddress space websitename Eg: 192.168.30.03 ann.rset 8. Execute command : a2ensite ann.rset This is to inform apache server, about the addition of new host in hosts file. 9. Adding an ftp user 1. Execute command : sudo gadmin-proftpd start 2. Add password at the server and click apply to get certificate 3. click users and click new user 3.1. give the user name,password(greater than 6 char) 3.2. bin/bash 3.3. at last click add directory and select www/web and tick all permissions. 3.4. click apply 10. Execute command : sudo /etc/init.d/apache2 restart :sudo /etc/init.d/proftpd start 11. Open browser and type ann.rset and you will see the index.html you created inside /www/web/ 12. Now open filezilla Execute Command: sudo filezilla 13. Use IP address and username ,password to connect the ftp server and transfer files to the web .

Conclusion FTP is installed and Mentioned familiarization the experiments were successfully completed.

University Register No:

73

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 04 Date:29-10-2012

IMPLEMENTATION OF NFS

PROBLEM DEFINITION Implement NFS and familiarize its functions.

THEORETICAL BACKGROUND Network File System (NFS) is a distributed file system protocol originally developed by Sun Microsystems in 1984, allowing a user on a client computer to access files over a network in a manner similar to how local storage is accessed. NFS, like many other protocols, builds on the Open Network Computing Remote Procedure Call (ONC RPC) system. The Network File System is an open standard defined in RFCs, allowing anyone to implement the protocol. The Network File System is certainly one of the most widely used network services. Network file system (NFS) is based on the Remote procedure call which allows the client to automatically mount remote file systems and therefore transparently provide an access to it as if the file system is local. For example, if you were using a computer linked to a second computer via NFS, you could access files on the second computer as if they resided in a directory on the first computer. This is accomplished through the processes of exporting (the process by which an NFS server provides remote clients with access to its files) and mounting (the process by which file systems are made available to the operating system and the user). The NFS protocol is designed to be independent of the computer, operating system, network architecture, and transport protocol. This means that systems using the NFS service may be manufactured by different vendors, use different operating systems, and be connected to networks with different architectures. These differences are transparent to the NFS application, and thus, the user.

University Register No:

74

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROBLEM DEVELOPMENT In this scenario we are going to export the file system from the an IP address 192.168.30.3 ( NFS server ) host and mount it on an a host with an IP address 192.168.30.5 ( NFS Client ). Both NFS server and NFS client will be running Ubuntu.

Installation Step 1: # apt-get install nfs-common Installing nfs-common package on both NFS client and NFS server using using aptget tool. The command above will fetch and install all support files common to NFS client and NFS server including portmap. Step 2: apt-get install nfs-kernel-server This package is the actual NFS daemon listenning on both UDP and TCP 2049 ports. Step 3: rpcinfo -p | grep nfs Execute rpcinfo -p to check correctness of your NFS installation Ouput if installed correctly 100003 100003 100003 100003 100003 100003 2 udp 2049 nfs 3 udp 2049 nfs 4 udp 2049 nfs 2 tcp 2049 nfs 3 tcp 2049 nfs 4 tcp 2049 nfs

Step 4: # cat /proc/filesystems | grep nfs To check whether your system supports NFS Output if it supports
University Register No:

75

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

nodev nfs nodev nfs4

Step 5: # modprobe nfs If you do not see any output it means that NFS is not supported or the NFS modules have not been loaded into your kernel. To load NFS module execute the above command

Server export file

All directories we want to share over the network using NFS need to be defined on the server side of this communication and more specifically they need to be defined with /etc/exports file. The most common NFS export techniques and options:
a) /home/nfs/ 10.1.1.55(rw,sync)

export /home/nfs directory for host with an IP address 10.1.1.55 with read, write permissions, and synchronized mode.

b) /home/nfs/ 10.1.1.0/24(ro,sync)

export /home/nfs directory for network 10.1.1.0 with netmask 255.255.255.0 with read only permissions and synchronized mode.

c) /home/nfs/ 10.1.1.55(rw,sync) 10.1.1.10(ro,sync)

export /home/nfs directory for host with IP 10.1.1.55with read, write permissions, synchronized mode, and also export /home/nfs directory for another host with an IP address 10.1.1.10 with read only permissions and synchronized mode.

d) /home/nfs/ 10.1.1.55(rw,sync,no_root_squash)

export /home/nfs directory for host with an IP address 10.1.1.55with read, write permissions, synchronized mode and the remote root user will be treated as a root and will be able to change any file and directory.
University Register No:

76

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

e) /home/nfs/ *(ro,sync)

export /home/nfs directory for any host with read only permissions and synchronized mode

f)

/home/nfs/ *.linuxcareer.com(ro,sync) export /home/nfs directory for any host within linuxconfig.org domain with a read only permission and synchronized mode.

g) /home/nfs/ foobar(rw,sync)

export /home/nfs directory for hostname foobar with read, write permissions and synchronized mode .

Edit exports file

Step 1: # echo '/home/nfs/ *(ro,sync)' > /etc/exports Simply insert your NFS export line into /etc/exports file using echo command: Step 2 : # touch /home/nfs/nfs-test-file Be sure that the directory you are about to export by NFS exists

Restart NFS daemon # /etc/init.d/nfs-kernel-server restart

Mount remote file system on client Step 1: # mkdir /home/nfs_local create a mount point:

University Register No:

77

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Step 2: # mount 192.168.30.3:/home/nfs /home/nfs_local

If you are sure that the NFS client and mount point are ready, you can run the mount command to mount exported NFS remote file system:

CONCLUSION NFS installed and Mentioned familiarization the experiments were successfully completed.

University Register No:

78

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 5 Date: 5-11-2012

IMPLEMENTATION OF REMOTE LOGIN

PROBLEM DEFINITION Implement 1. XDMCP(X Display Manager Control Protocol) 2. Implement SSH and try following experiments.

i. ii.

Password-less login with SSH. MAC verification during SSH login.

THEORETICAL BACKGROUND XDMCP(X Display Manager Control Protocol) In the X Window System, an X display manager runs as a program that allows the starting of a session on an X server from the same or another computer. A display manager presents the user with a login screen which prompts for a username and password. A session starts when the user successfully enters a valid combination of username and password. When the display manager runs on the user's computer, it starts the X server before presenting the user the login screen, optionally repeating when the user logs out. In this condition, the display manager realizes in the X Window System the functionality of getty and
login

on character-mode terminals. When the display manager runs on a remote computer, it

acts like a telnet server, requesting username and password and starting a remote session. X11 Release 3 introduced display managers in October 1988 with the aim of supporting the standalone X terminals. X11R4 introduced the X Display Manager Control Protocol (XDMCP) in December 1989 to fix problems in the X11R3 implementation. a. Local and remote display management A display manager can run on the same computer where the user sits or on a remote
University Register No:

79

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

one. In the first case, the display manager starts one or more X servers, displaying the login screen at the beginning and (optionally) every time the user logs out. In the second case, the display manager works according to the XDMCP protocol. In the X Window System, the X server runs on the computer in front of the user. The X server may connect to a display manager running on another computer, starting a session which may comprise a variety of programs running on that other computer. The XDMCP protocol mandates that the X server starts autonomously and connects to the display manager. In the X Window System paradigm, the server runs on the computer providing the display and input devices. A server can connect, using the XDMCP protocol, to a display manager running on another computer, requesting it to start the session. In this case, the X server acts as a graphical telnet client while the display manager acts like a telnet server: users start programs from the computer running the display manager, while their input and output take place on the computer where the server (and the user) sits. In the X Window System, the X server runs on the computer in front of the user. The X server may connect to a display manager running on another computer, starting a session which may comprise a variety of programs running on that other computer.

Fig 1. X Window System


University Register No:

80

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

An administrator can typically configure an XDMCP Chooser program running on the local computer or X terminal to connect to a specific host's X display manager or display a list of suitable hosts that the user can choose from. Most implementations enabled such a list to contain: 1. a predefined set of hosts and their respective network addresses, and/or 2. a set of hosts (on the local TCP/IP subnet) that the XDMCP Chooser determines by a network broadcast to the available display managers. When the user selects a host from the list, the XDMCP Chooser running on the local machine will send a message to the selected remote computer's display manager and instruct it to connect the X server on the local computer or terminal. b. X Display Manager Control Protocol The X Display Manager Control Protocol uses UDP port 177. An X server requests that a display manager start a session by sending a Query packet. If the display manager allows access for that X server, it responds by sending a willing packet back to the X server. The display manager must authenticate itself to the server. To do this the X server sends a
Request

packet to the display manager, which returns an Accept packet. If the Accept packet

contains the response the X server expects, the display manager is authenticated. Producing the correct response might require the display manager to have access to a secret key, for example. If authentication succeeds, the X server sends a Manage packet to inform the display manager. Then the display manager displays its login screen by connecting to the X server as a regular X client. During the session, the server can send Keep Alive packets to the display manager at intervals. If the display manager fails to respond with an Alive packet within a certain time, the X server presumes that the display manager has ceased running, and can terminate the connection. The X Window System supplies XDM as its standard display manager. Programmers
University Register No:

81

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

have developed other X display managers, both commercial and free, offering additional functionality over the basic display management.

SSH

Secure Shell (SSH) is a cryptographic network protocol for secure data communication, remote shell services or command execution and other secure network services between two networked computers that connects, via a secure channel over an insecure network, a server and a client (running SSH server and SSH client programs, respectively). The best-known application of the protocol is for access to shell accounts on Unix-like operating systems. It was designed as a replacement for Telnet and other insecure remote shell protocols. The encryption used by SSH is intended to provide confidentiality and integrity of data over an unsecured network, such as the Internet. SSH uses public-key cryptography to authenticate the remote computer and allow it to authenticate the user, if necessary. Anyone can produce a matching pair of different keys (public and private). The public key is placed on all computers that must allow access to the owner of the matching private key (the owner keeps the private key secret). While authentication is based on the private key, the key itself is never transferred through the network during authentication. SSH only verifies whether the same person offering the public key also owns the matching private key. Hence, in all versions of SSH it is important to verify unknown public keys, i.e. associate the public keys with identities, before accepting them as valid. Accepting an attacker's public key without validation will authorize an unauthorized attacker as a valid user. Key management On Unix-like systems, the list of authorized keys is stored in the home directory of the user that is allowed to log in remotely, in the file ~/.ssh/authorized_keys. This file is only respected by ssh if it is not writable by anything apart from the owner and root. When the public key is present on one side and the matching private key is present on another side,
University Register No:

82

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

typing in the password is no longer required (some software like MPI stack may need this password-less access to run properly). However, for additional security the private key itself can be locked with a passphrase. The private key can also be looked for in standard places, but its full path can also be specified as a command line setting (the switch -i for ssh). The ssh-keygen utility produces the public and private keys, always in pairs.SSH also supports password-based authentication that is encrypted by automatically generated keys. In this case the attacker could imitate the legitimate side, ask for the password and obtain it (man-in-themiddle attack). However this is only possible if the two sides have never authenticated before, as SSH remembers the key that the remote side once used. Password authentication can be disabled. Usage SSH is typically used to log into a remote machine and execute commands, but it also supports tunneling, forwarding TCP ports and X11 connections; it can transfer files using the associated SSH file transfer (SFTP) or secure copy (SCP) protocols. SSH uses the clientserver model. The standard TCP port 22 has been assigned for contacting SSH servers. i. Open-SSH SSH released under an open source license. Open-SSH was the single most popular SSH implementation, coming by default in a large number of operating systems. It is estimated that, as of 2000, there were 2 million users of SSH.

PROGRAM DEVELOPMENT A. XDMCP 1. create the file "custom.conf" under /etc/gdm/ with the following contents: [daemon] RemoteGreeter=/usr/lib/gdm/gdmlogin
University Register No:

83

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

[xdmcp] Enable=true

2. To enable XDMCP in tsclient at the client machine: sudo apt-get install xnest

3. Then restart GDM, either by restarting the entire computer or running the following command (log out locally before you run this!): sudo service gdm restart 4. Then type sudo tsclient

5. Use IP address of host machine and select protocol as "XDMCP".

6. New login window appears. Successful login creates a new session.

a. Install SSH server. Here, we use Open-SSH for implementation. Open-SSH is a FREE version of the SSH connectivity tools that technical users of the Internet. Open-SSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks.

Steps I. Search compactable packet available for your Ubuntu version. sudo apt-cache search openssh-server II. In Ubuntu 10.04, packages available. To install the Open-SSH server. sudo apt-get install openssh-server To install the Open-SSH client. sudo apt-get install openssh-client
University Register No:

84

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

III.

Starting service. Sudo service ssh restart

b. Password-less logins with Open-SSH To enable the remote login you create a pair of keys, one of which you simply append to a file upon the remote system. When this is done you'll then be able to login without being prompted for a password.

If you don't already have a key pair generated you'll first of all need to create one. To generate a new key pair you run the following command: ssh-keygen -t rsa

This will prompt you for a location to save the keys, and a pass-phrase: Generating public/private rsa key pair. Enter file in which to save the key (/home/skx/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/skx/.ssh/id_rsa. Your public key has been saved in /home/skx/.ssh/id_rsa.pub.

If you accept the defaults you'll have a pair of files created, as shown above, with no passphrase. This means that the key files can be used as they are, without being "unlocked" with a password first. If you're wishing to automate things this is what you want.Now that you have a pair of keyfiles generated, or pre-existing, you need to append the contents of the .pub file to the correct location on the remote server. Assuming that you wish to login to the machine called mystery from your current host with the
id_rsa

and id_rsa.pub files you've just generated you should run the following command: ssh-copy-id -i ~/.ssh/id_rsa.pub username@mystery

University Register No:

85

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

In our system username@mystery replace with root@localhost. This will prompt you for the login password for the host, then copy the keyfile for you, creating the correct directory and fixing the permissions as necessary. The contents of the keyfile will be appended to the file ~/.ssh/authorized_keys2 for RSA keys. Once this has been done you should be able to login remotely, and run commands, without being prompted for a password: skx@lappy:~$ ssh mystery uptime 09:52:50 up 96 days, 13:45, 0 users, load average: 0.00, 0.00, 0.00

What if it doesn't work? There are three common problems when setting up password less logins:

The remote SSH server hasn't been setup to allow public key authentication. File permissions cause problems. Your key type isn't supported.

Each of these problems is easily fixable, although the first will require you have root privileges upon the remote host. If the remote server doesn't allow public key based logins you will need to updated the SSH configuration. To do this edit the file /etc/sshd/sshd_config with your favorite text editor. You will need to uncomment, or add, the following two lines: RSAAuthentication yes PubkeyAuthentication yes

Once that's been done you can restart the SSH server - don't worry this won't kill existing sessions:

/etc/init.d/ssh restart

c. MAC verification during SSH login. The logical reason behind this experiment, usually person in multi co-operate company login
University Register No:

86

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

the remote site within the company perimeter. Because the employees handling sensitive information. Avoid tapping important information. Company usually doesnt permits use of personal computer for office use. Only login the remote site inside the company by using there facility. That means login from a set of already registered computer. For that we usually follow MAC id verification. Before doing this we have some generalized ides about Firewall and its working. Firewall is a technological barrier designed to prevent unauthorized or unwanted communications between computer networks or hosts. iptables is the tables provided by the Linux kernel firewall and the chains and rules it stores. iptables requires elevated privileges to operate and must be executed by user root, otherwise it fails to function. On most Linux systems, iptables is installed as /usr/sbin/iptables and documented in its man pages which can be opened using man iptables when installed.

Basic Linux Firewall iptable Rules for this experiment : To get current rules in iptable iptables --list iptables -L INPUT -n --line-numbers

Removing all currently existing rules iptables flush

Steps

Removing a rule already existing in the iptables iptables -D INPUT [no]

1. For system registration, we want MAC id of the computer. For that remote login the registering machine. ssh root@[ip address] 2. For MAC id ifconfig 3. To get current rules in iptable. Use command already mentioned. 4. Add new rule to iptable. Accept all incoming request from corresponding MAC id.

sudo iptables -A INPUT -m mac --mac-source [MAC id] -p tcp --dport ssh -j ACCEPT

University Register No:

87

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

5. Add new rule to iptable. Refuse all incoming connection requests to a local port 23{ iptable follow the rule from top to bottom. So this rule not affect already registered computer} sudo iptables -A INPUT -p tcp --dport ssh -j REJECT

6. To save configuration.

iptables-save

The above commands make system more reliable for incoming request. Only accept request from registered computer. In other works all ssh connections will be limited to a single host.

CONCLUSION XDMCP and SSH are successfully implemented and result is obtained.

University Register No:

88

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 6 Date: 12-11-2012

IMPLEMENTATION OF E-MAIL SERVER

PROBLEM DEFINITION E-mail Server Configuration and Management using Exim and Squirrel Mail

THEORETICAL BACKGROUND Often referred to as simply "mail server", an e-mail server is a computer within your network that works as your virtual post office. A mail server usually consists of a storage area where e-mail is stored for local users, a set of user definable rules which determine how the mail server should react to the destination of a specific message, a database of user accounts that the mail server recognizes and will deal with locally, and communications modules which are the components that actually handle the transfer of messages to and from other mail servers and email clients. Mail servers can be broken down into two main categories: outgoing mail servers and incoming mail servers. Outgoing mail servers are known as SMTP, or Simple Mail Transfer Protocol, servers. Incoming mail servers come in two main varieties. POP3, or Post Office Protocol, version 3, servers are best known for storing sent and received messages on PCs' local hard drives. IMAP, or Internet Message Access Protocol, servers always store copies of messages on servers. Most POP3 servers can store messages on servers, too, which is a lot more convenient. The Process of Sending an Email Step #1: After composing a message and hitting send, your email client - whether it's Outlook Express or Gmail - connects to your domain's SMTP server. This server can be named many things; a standard example would be smtp.example.com. Step #2: Your email client communicates with the SMTP server, giving it your email address,
University Register No:

89

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

the recipient's email address, the message body and any attachments. Step #3: The SMTP server processes the recipient's email address - especially its domain. If the domain name is the same as the sender's, the message is routed directly over to the domain's POP3 or IMAP server - no routing between servers is needed. If the domain is different, though, the SMTP server will have to communicate with the other domain's server. Step #4: In order to find the recipient's server, the sender's SMTP server has to communicate with the DNS, or Domain Name Server. The DNS takes the recipient's email domain name and translates it into an IP address. The sender's SMTP server cannot route an email properly with a domain name alone; an IP address is a unique number that is assigned to every computer that is connected to the Internet. By knowing this information, an outgoing mail server can perform its work more efficiently. Step #5: Now that the SMTP server has the recipient's IP address, it can connect to its SMTP server. This isn't usually done directly, though; instead, the message is routed along a series of unrelated SMTP servers until it arrives at its destination. Step #6: The recipient's SMTP server scans the incoming message. If it recognizes the domain and the user name, it forwards the message along to the domain's POP3 or IMAP server. From there, it is placed in a send mail queue until the recipient's email client allows it to be downloaded. At that point, the message can be read by the recipient. SQUIRRELMAIL SquirrelMail is an Open Source project that provides both a web-based email application and an IMAP proxy server. The webmail portion of the project was started by Nathan and Luke Ehresman in 1999 and is written in the PHP scripting language. It can be installed on almost all web servers as long as PHP is present and the web server has access to an IMAP and SMTP server. The SquirrelMail IMAP proxy server product was adopted by the SquirrelMail team in 2010.It is written in C and is primarily made to provide stateful connections for stateless webmail client software to an IMAP server, thus avoiding new IMAP logins for every client action and in some cases significantly improving webmail performance. SquirrelMail webmail is available for any platform supporting PHP. Most commonly used platforms include Linux, FreeBSD, Mac OS X and the server variants of Microsoft Windows.
University Register No:

90

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

SquirrelMail IMAP Proxy compiles on most flavors of UNIX, and can generally be used on the same platforms as the webmail product can be with the exception of Microsoft Windows, unless used in a Cygwin or similar environment. EXIM Exim is a mail transfer agent (MTA) used on Unix-like operating systems. Exim is free software distributed under the terms of the GNU General Public License, and it aims to be a general and flexible mailer with extensive facilities for checking incoming e-mail. Exim has been ported to most Unix-like systems, as well as to Microsoft Windows using the Cygwin emulation layer. Exim 4 is currently the default MTA on Debian GNU/Linux systems.A large number of Exim installations exist, especially within Internet service providers and universities in the UK. Exim is also widely used with the GNU Mailman mailing list manager, and cPanel. Exim, like Smail, still follows the Sendmail design model, where a single binary controls all the facilities of the MTA. This monolithic design is considered by some to be inherently less secure, due to the lack of binary separation between the individual components of the system[citation needed]. Instead, Exim separates the components out in terms of invocation and has well-defined stages during which it gains or loses privileges. Exims security record has been fairly clean, with only a handful of serious security problems diagnosed over the years. Since the redesigned version 4 was released there have been four remote code execution flaws and one conceptual flaw concerning how much trust it is appropriate to place in the run-time user; the latter was fixed in a security lockdown in revision 4.73, one of the very rare occasions when Exim has broken backwards compatibility with working configurations. This issue would not have been prevented by using a nonmonolithic design. This high degree of cleanliness is probably due to having been written from scratch and with security in mind, by an experienced developer (who was not responsible for two of the three remote code execution flaws).

University Register No:

91

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROGRAM DEVELOPMENT 1. apt-get install exim4-daemon-heavy exim4 courier-base courier-authdaemon courierimap courier-pop maildrop squirrelmail. It installs SquirrelMail at /usr/share/squirrelmail directory and the

configuration files will be under /etc/squirrel/ directory. 2. Configuration of utilities Exim4 Run the command dpkg-reconfigure exim4-config This takes to a wizard to configure and has multiple screens one-byone. The first screen Here it asks if multiple configuration files are required or all configurations can be merged into a single file and use that. Answer no to question on split. We can keep the whole configuration in a single file.

Type of mail configuration

System mail name IP Address to listen on for incoming connections Domains to relay mail for(keeps this empty) Machines to relay mail for(keep this empty) DNS queries to be kept minimum( this can be answered as no) Keep mail in Maildir format in home directory

At the end of this, the Exim4 will be restarted.

Then we also need to set our mail delivery program to maildrop which delivers mail in a Mail Directory format. This can be done by editing the file /etc/exim4/update-exim4.conf and
University Register No:

92

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

adding a line

dc_localdelivery=maildir_home

Restart the process.

3. Creating User accounts

For creating user accounts, the following command can be used

useradd m <userid>

We also need to create the mail account and directory format by the command maildirmake ~<userid>/Maildir maildirmake q <quota in bytes>S ~<userid>/Maildir chown R <userid>:<userid> ~<userid>

4. Configuring SquirrelMail

SquirrelMail can be configured by running /usr/sbin/squirrelmail-configure This program is a window/menu oriented one and can easily be configured. 5. Apache Configuration

Squirrelmail

comes

with

sample

apache

configuration

file

in

/etc/squirrelmail/apache.conf. You can copy this file to /etc/apache2/sitesavailable/squirrelmail with the command: sudo cp /etc/squirrelmail/apache.conf /etc/apache2/sites-available/squirrelmail Then link it to the sites-enabled directory with the command: sudo ln s /etc/apache2/sites-available/squirrelmail/ etc/apache2/sitesenabled/squirrelmail Alternatively one can use the a2ensite tool:
University Register No:

93

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

sudo a2ensite squirrelmail Reload Apache Configuration: sudo /etc/init.d/apache2 force-reload

CONCLUSION E-mail server installed, Mentioned familiarization experiments were successfully completed.

University Register No:

94

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 7 Date: 19-11-2012

IMPLEMENTATION OF DNS SERVER

PROBLEM DEFINITION Implement the DNS server and familiarize its application.

THEORETICAL BACKGROUND To identify an entity, the internet uses IP address, which uniquely identifies the connection of a host to the internet. However the people prefer to use names instead of numeric address. Therefore we need a system that can map a name to an address or an address to a name. When the internet was small, mapping was done using a host file. The host file had only two columns, one for name and one for address. But it is impossible to have one single host file relate every address to a name and vice versa. One solution would be to store the entire host file in a single computer and allow access to this centralized information to every computer that needs a mapping. But we know that this would create a huge traffic on the internet. Another solution is to divide this huge amount of information into smaller parts and store each part on a different computer.in this method the host that needs mapping can contact the closest computer holding the needed information. This method is used by the Domain name system (DNS). Name space: To be unambiguous, the names assigned to machine must be carefully selected from a name space with complete control over the binding between the name and the IP address. In other words the name must be unique because the addresses are unique. A name space that maps each address to a unique name can be organized in two different ways: flat and hierarchical. Flat name space: In a file name space, a name is assigned to an address. A name in this space is a sequence of characters without structure. The name may or may not have a common section. If they do, it has no meaning. The main disadvantage of a flat name space is that it cannot be
University Register No:

95

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

used in a large system such as the internet because it must be carefully controlled to avoid ambiguity and duplication. Hierarchical name space: In hierarchical name space, each name is made of several parts. The first part can define the nature of organization, the second part can define the name, and the third part can define the department, and so on. In this case, the authority to assign the name and space can be decentralized. A central authority can assign the part of the name tha defines the nature of the organization and the name. The responsibility for the rest of the name can be given to the organization itself. Domain Name Space: To have a hierarchical name space, a domain name space was designed. In this design, the names are defined in an inverted tree structure with the root at the top. The tree can have 128 levels: level 0 to level 127. Label Each node in the tree has a label, which is a string with a maximum of 63 characters. The root label is a null string. DNS requires that children of a node have different labels, which guarantee the uniqueness of the domain names. Domain name: Each node in the tree has a domain name. A full domain name is a sequence of labels separated by dots. The domain name s are always read from the node up to the root. The last label is the label of root(null). This means that a full domain name always ends with a null label, which means that the last label is a dot.

Distribution of Name Space: The information contained in the domain name space must be stored. However it is very inefficient and also not reliable to have just one computer store such a huge amount of information. It is inefficient because responding to request from all over the world places a heavy load on the system. It is not reliable because any failure makes the data inaccessible. Hierarchy of Name Servers: The solution to these problems is to distribute the information among many computers called DNS Server. One way to do this is to divide the whole space into many domains based on the first level. In other words, let the root stand alone and create as many domains (sub
University Register No:

96

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

tree) as there are first-level nodes. Because a domain created this way could be very large, DNS allows domains to be divided further into smaller domains (subdomains). Each server can be be responsible for either a large or a small domain. In other words, we have a hierarchy of servers in the same way that we have a hierarchy of names. Zones: What a server is responsible for, or has authority over is called zones. If the server accepts responsibility for a domain and does not divide the domain into smaller domains, the domain and the zone refer to the same thing. The server makes a database called zone file and keep all the information for every node under that domain. However, if a server divides its domain into subdomains and delegates part of its authority to other servers, domain and zone refer to different thing. The information about the nodes in the subdomain is stored in the server at low level, with the original server keeping some sort of references to these lower level servers. Of course the original server does not free itself from responsibility totally, it still has a zone, but the detailedinformation is kept by the lower level servers. Resolution Mapping a name to an address or an address to a name is called name-address resolution. Resolver DNS is designed as a client server application. A host that needs to map an address to a name or name to an address called a DNS client named a resolver. The resolver access the closest DNS server with a mapping request. If the server has the information, it satisfies the resolver: otherwise, it either refers the resolver to other severs. After the resolver receives the mapping it interprets the response to see if it is a real solution or an error and finally deliver the result to the process that requested it. Mapping names to addresses: Most of the time, the resolver gives a domain name to the server and ask for the corresponding address. In this case, the server checks the generic domains or the country domain to find the mapping. If the domain name is from the generic domain section, the resolver receives a domain name such as chal.atc.fhda.edu. . The query is send by the resolver to the local DNS server for resolution. If the local server cannot resolve the query,it either refers the resolver to the other servers or asks other servers directly. If the domain name is from the country domain section, the resolver receives a domain name such as ch.fhda.cu.ca.us. . The procedure is the same.
University Register No:

97

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Mapping addresses to names: A client can send an IP address to a server to be mapped to a domain name. to answer queries of this kind, DNS uses the inverse domain. However ,in the request the IP address is reversed, and two labels in-addr and arpa, are appended to create a domain acceptable by the inverse domain section. DNS message format: A DNS Message Format contains 5 sections: 1. Header - Includes: 1. Bits 0-15 are the query identifier 2. Bit 16 - QR bit, The message is a query if the value is 0. The message is a response if the value is 1/ 3. Bits 17-20 - Opcode values - Identifies the query type. The message is a standard query if 0, The message is an inverse query if 1, The message is a server status request if 2. 4. Bit 21 - AA - Authoritative answer - If set, it indicates the responding name server is an aurhority for the domain name in question. 5. Bit 22 - TC - Indicates the message was truncated. 6. Bit 23 - RD - Recursion Desired - Set in a query and indicates the query should be persued recursively. 7. Bit 24 - RA - Recursion Available - A bit that is set or cleared in a response indicating that recursion is available. 8. Bit 25-27 - Z - Future use, required to always be 0 9. Bit 28-31 - RCODE - Response code - No error if 0, Format error if 1, Server failure if 2 10. Word 3 - QDCOUNT - Indicates the number of DNS querise (entries in the question section) 11. Word 4 - ANCOUNT - Indicates the number of answers (Resource records in
University Register No:

98

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

the answer section) 12. Word 5 - NSCOUNT - The number of name server records in the authority records section. 13. Word 6 - ARCOUNT - The number of resource records in the additional records section. 2. Question - Includes: 1. QNAME - Domain name strings with a length byte followed by a string of the designated length. 2. QTYPE - Two bytes indicating the query type 3. QCLASS - Two bytes indicating the class field such as IN for internet. 3. Answer - Resource Records (RRs) answering the question 1. NAME - domain name 2. TYPE - Two bytes with resource record type. 3. CLASS - Two bytes indicating the class of the data 4. TTL - A 32 bit unsigned integer indicating the time interval in seconds that the may be stored on the DNS server. 5. RDLENGTH - 16 bits indicating the length of the RDATA field in bytes. 6. RDATA - This may be the IP address for a domain name but the information varies depending on the type and class of the resource record. 4. Authority - Resource Records (RRs) pointing to an authority - The format is the same as the Answer section. 5. Additional - Resource Records (RRs) holding additional information - The format is the same as the Answer section.

University Register No:

99

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROGRAM DEVELOPMENT Installing Bind in Ubuntu sudo apt-get install bind9 dnsutils This will install all the required packages for bind9 Configuring Bind If you install Bind from the source code, you will have to edit the file named.conf. However, Ubuntu provides you with a pre-configured Bind, so we will edit named.conf.local file sudo vi /etc/bind/named.conf.local This is where we will insert our zones.If you want to know what is zone in DNs check this You need to add the following lines in named.conf.local file # This is the zone definition. replace example.com with your domain name Zone example.com" { type file }; # This is the zone definition for reverse DNS. Replace 0.168.192 with your network address in reverse notation -- e.g my network address is 192.168.0 Zone "0.168.192.in-addr.arpa" { type file }; Now you need to edit the options file sudo vi /etc/bind/named.conf.options We need to modify the forwarder. This is the DNS server to which your own DNS will forward the requests he cannot process. forwarders {# Replace the address below with the address of your provider's DNS server 123.123.123.123;}; add the zone definition files (replace example.com with your domain name sudo mkdir /etc/bind/zones sudo vi /etc/bind/zones/example.com.db
University Register No:

master; "/etc/bind/zones/example.com.db";

master; "/etc/bind/zones/rev.0.168.192.in-addr.arpa";

100

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

The zone definition file is where we will put all the addresses / machine names that our DNS server will know.Example zone file as follows // replace example.com with your domain name. do not forget the . after the domain name! // Also, replace ns1 with the name of your DNS server example.com. IN SOA ns1.example.com.admin.example.com.( // Do not modify the following lines! 2007031001 28800 3600 604800 38400 ) // Replace the following line as necessary: // ns1 = DNS Server name // mail = mail server name // example.com = domain name example.com. IN NS ns1.example.com. example.com. IN MX 10 mail.example.com. // Replace the IP address with the right IP addresses. www IN A 192.168.0.2 mta IN A 192.168.0.3 ns1 IN A 192.168.0.1 Create Reverse DNS Zone file A normal DNS query would be of the form what is the IP of host=www in domain=mydomain.com'. There are times however when we want to be able to find out the name of the host whose IP address = x.x.x.x. Sometimes this is required for diagnostic purposes more frequently these days it is used for security purposes to trace a hacker or spammer, indeed many modern mailing systems use reverse mapping to provide simple authentication using dual look-up, IP to name and name to IP. In order to perform Reverse Mapping and to support normal recursive and Iterative (nonrecursive) queries the DNS designers defined a special (reserved) Domain Name called INADDR.ARPA. This domain allows for all supported Internet IPv4 addresses (and now IPv6). sudo vi /etc/bind/zones/rev.0.168.192.in-addr.arpa
University Register No:

101

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

copy and paste the following sample file //replace example.com with your domain name, ns1 with your DNS server name. // The number before IN PTR example.com is the machine address of the DNS server. in my case, it's 1, as my IP address is 192.168.0.1. @ IN SOA ns1.example.com. admin.example.com. ( 2007031001; 28800; 604800; 604800; 86400 ) IN NS ns1.example.com. 1 IN PTR example.com Restart Bind server using the following command sudo /etc/init.d/bind9 restart Testing Your DNS Server Modify the file resolv.conf with the following settings sudo vi /etc/resolv.conf Enter the following details save and exit the file // replace example.com with your domain name, and 192.168.0.1 with the address of your new DNS server. search example.com nameserver 192.168.0.1 Test your DNS Using the following command dig example.com

CONCLUSION The DNS server was successfully installed and its functionalities were familiarized.

University Register No:

102

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 8 Date:26-11-2012

IMPLEMENTATION OF DHCP

PROBLEM DEFINITION Implement DHCP and try following experiments. Install DHCP server and client. Client obtains IP address from DHCP server.

THEORETICAL BACKGROUND The Internet is a vast source of information that is continuously updated and accessed via computers and other devices. For a device (also referred to as a host) to connect to the Internet, it is necessary that among other configurations, it must have an Internet Protocol (IP) address. The IP address is the computer's address on the Internet. A common comparison of an IP address is an individual's telephone number, which is an identifier for people to communicate with the individual. Up until the late 1980s, configuring a computer to connect to the Internet was a manual process. The protocol Bootstrap Protocol (BOOTP) was the first Transmission Control Protocol/Internet Protocol (TCP/IP) network configuration tool used to prevent the task of having to manually assign IP addresses by automating the process. While the introduction of the BOOTP network protocol was a welcome innovation for network administrators tasked with managing large numbers of computers on a network, it was the first attempt and a new and improved TCP/IP network protocol soon followed. This protocol is called Dynamic Host Configuration Protocol (DHCP). DHCP was not designed as a replacement for BOOTP, but an extension of its functionality.

University Register No:

103

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

How DHCP Works As its name indicates, DHCP provides dynamic IP address assignment. What this means is that instead of having to rely on a specific IP address, a computer will be assigned one that is available from a subnet or "pool" that is assigned to the network. DHCP also extends BOOTP functionality to provide IP addresses that expire. BOOTP indirectly uses a form of leasing that never expired, but the term wasn't actually used until the introduction of DHCP. When DHCP assigns an IP address, it actually leases the identifier to the host computer for a specific amount of time. The default lease is five days, but a network administrator should evaluate their own particular circumstances to determine an appropriate lease. The DHCP lease process works as follows: 1. A network device attempts to connect to the Internet. 2. The network requests an IP address. 3. The DHCP server allocates (leases) the network device an IP address, which is forwarded to the network by a router. 4. DHCP updates the appropriate network servers with the IP address and other configuration information. 5. The network device accepts the IP address. 6. The IP address lease expires. 7. DHCP either reallocates the IP address or leases one that is available. 8. The network device is no longer connected to the Internet. 9. The IP address becomes an available address in the network pool of IP addresses.
University Register No:

104

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

To set up DHCP, you basically need a DHCP-supported client (at least one) and router, and a DHCP server. The client is a computer or other device on a network that requires an IP address and or other network configuration information. The router functions as a forwarding (or routing) agent of IP address requests from the DHCP server. The DHCP server is key to the entire operation. It is responsible for allocating, leasing, reallocating, and renewing IP addresses. Windows and Linux both support DHCP software. Configuration A DHCP server can provide configuration settings using two methods: Address Pool This method entails defining a pool (sometimes also called a range or scope) of IP addresses from which DHCP clients are supplied their configuration properties dynamically and on a fist come first serve basis. When a DHCP client is no longer on the network for a specified period, the configuration is expired and released back to the address pool for use by other DHCP Clients. MAC Address This method entails using DHCP to identify the unique hardware address of each network card connected to the network and then continually supplying a constant configuration each time the DHCP client makes a request to the DHCP server using that network device.

PROGRAM DEVELOPMENT The DHCP client and server configurations are done based on address pooling method.The following are the steps involved in this.

Configuring DHCP server Step 1: Install DHCP server in ubuntu

sudo apt-get install dhcp3-server


University Register No:

105

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Step 2: backup copy of /etc/dhcp3/dhcpd.conf file is to be made. cp /etc/dhcp3/dhcpd.conf /etc/dhcp3/dhcpd.conf.back

Step 3: Edit the conf file of dhcp server

sudo gedit /etc/dhcp3/dhcpd.conf

Make the following changes default-lease-time max-lease-time 7200; option option option option subnet-mask broadcast-address routers domain-name-servers 192.168.50.1, 255.255.255.0; 192.168.50.255; 192.168.50.254; 192.168.50.2; 600;

option domain-name "mydomainname.com"; subnet range } Step 4: Restart the DHCP server. sudo /etc/init.d/dhcp3-server restart 192.168.50.0 netmask 255.255.255.0 {

192.168.50.10

192.168.50.20;

Configuring DHCP Client Step 1:Make the following changes in the interface file: sudo gedit /etc/network/interfaces

University Register No:

106

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

auto lo eth0 iface eth0 inet dhcp iface lo inet loopback

Step 2: restart networking services using the following command sudo /etc/init.d/networking restart How to find DHCP server IP address Use the following commands sudo dhclient

CONCLUSION DHCP installed, Mentioned familiarization experiments were successfully completed.

University Register No:

107

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 9 Date:3-12-2012

IMPLEMENTATION OF DATABASE SERVER ADMINISTRATION- MYSQL

PROBLEM DEFINITION Implement and learn the basic functionality of MySQL.

THEORETICAL BACKGROUND MySQL is the world's most used open source relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases. It is named after co-founder Michael Widenius' daughter, My. The SQL phrase stands for Structured Query Language. The MySQL development project has made its source code available under the terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL was owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now owned by Oracle Corporation.MySQL is a popular choice of database for use in web applications, and is a central component of the widely used LAMP open source web application software stack (and other 'AMP' stacks) . LAMP is an acronym for "Linux, Apache, MySQL, Perl/PHP/Python." Free-software-open source projects that require a full-featured database management system often use MySQL. For commercial use, several paid editions are available, and offer additional functionality. Applications which use MySQL databases include: TYPO3, Joomla, WordPress, phpBB, MyBB, Drupal and other software built on the LAMP software stack. MySQL is also used in many high-profile, large-scale World Wide Web products, including Wikipedia, Google(though not for searches), Facebook, Twitter, Flickr, Nokia.com, and

YouTube.MySQL is an RDBMS and ships with no GUI tools to administer MySQL databases or manage data contained within the databases. Users may use the included command line tools, or use MySQL "front-ends", desktop software and web applications that create and manage MySQL databases, build database structures, back up data, inspect status,
University Register No:

108

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

and work with data records. The official set of MySQL front-end tools, MySQL Workbench is actively developed by Oracle, and is freely available for use. The official MySQL Workbench is a free integrated environment developed by MySQL AB, that enables users to graphically administer MySQL databases and visually design database structures. MySQL Workbench replaces the previous package of software, MySQL GUI Tools. Similar to other third-party packages, but still considered the authoritative MySQL frontend, MySQL Workbench lets users manage database design & modeling, SQL development (replacing MySQL Query Browser) and Database administration (replacing MySQL Administrator). MySQL works on many different system platforms, including AIX, BSDi, FreeBSD, HP-UX, eComStation, i5/OS, IRIX, Linux, Mac OS X, Microsoft Windows, NetBSD, Novell NetWare, OpenBSD, OpenSolaris, OS/2 Warp, QNX, Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos and Tru64. A port of MySQL to OpenVMS also exists.MySQL is written in C and C++. Its SQL parser is written in yacc, and a home-brewed lexical analyzer. Many programming languages with language-specific APIs include libraries for accessing MySQL databases. These include MySQL Connector/Net for integration with Microsoft's Visual Studio (languages such as C# and VB are most commonly used) and the JDBC driver for Java. In addition, an ODBC interface called MyODBC allows additional programming languages that support the ODBC interface to communicate with a MySQL database, such as ASP or ColdFusion. The HTSQL - URL-based query method also ships with a MySQL adapter, allowing direct interaction between a MySQL database and any web client via structured URLs. FEATURES As of April 2009, MySQL offered MySQL 5.1 in two different variants: the open source MySQL Community Server and the commercial Enterprise Server. MySQL 5.5 is offered under the same licences. They have a common code base and include the following features: A broad subset of ANSI SQL 99, as well as extensions Cross-platform support Stored procedures Triggers Cursors Updatable Views
109

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Information schema Strict mode (ensures MySQL does not truncate or otherwise modify data to conform to an underlying data type, when an incompatible value is inserted into that type)

Independent storage engines (MyISAM for read speed, InnoDB for transactions and referential integrity, MySQL Archive for storing historical data in little space)

SSL support Query caching Sub-SELECTs (i.e. nested SELECTs) Replication support (i.e. Master-Master Replication & Master-Slave Replication) with one master per slave, many slaves per master, no automatic support for multiple masters per slave.

Full-text indexing and searching using MyISAM engine Embedded database library Unicode support (however prior to 5.5.3 UTF-8 and UCS-2 encoded strings are limited to the BMP, in 5.5.3 and later use utf8mb4 for full unicode support)

Partitioned tables with pruning of partitions in optimizer Shared-nothing clustering through MySQL Cluster Hot backup (via mysqlhotcopy) under certain conditions Multiple storage engines, allowing one to choose the one that is most effective for each table in the application (in MySQL 5.0, storage engines must be compiled in; in MySQL 5.1, storage engines can be dynamically loaded at run time):

Native storage engines (MyISAM, Falcon, Merge, Memory (heap), Federated, Archive, CSV, Blackhole, Cluster, EXAMPLE, Maria, and InnoDB, which was made the default as of 5.5)

Partner-developed storage engines (solidDB, NitroEDB, ScaleDB, TokuDB, Infobright (formerly Brighthouse), Kickfire, XtraDB, IBM DB2).[36] InnoDB used to be a partner-developed storage engine, but with recent acquisitions, Oracle now owns both MySQL core and InnoDB.

Community-developed storage engines (memcache engine, httpd, PBXT, Revision Engine)

Custom storage engines Commit grouping, gathering multiple transactions from multiple connections together
110

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

to increase the number of commits per second. (PostgreSQL has an advanced form of this functionality LIMITATIONS Like other SQL databases, MySQL does not currently comply with the full SQL standard for some of the implemented functionality, including foreign key references when using some storage engines other than the 'standard' InnoDB.

Triggers are currently limited to one per action timing, i.e. maximum one after insert and one before insert on the same table. There are no triggers on views. MySQL, like most other transactional relational databases, is strongly limited by hard disk performance. This is especially true in terms of write latency. Given the recent appearance of very affordable consumer grade SATA interface Solid-state drives that offer zero mechanical latency, a fivefold speedup over even an eight drive RAID array can be had for a smaller investment.

PROGRAM DEVELOPMENT 1. First, open SPM (Synaptic Package Manager) from System->Administration>Synaptic Package Manager. 2. Search for MYSQL by using the Quick Search box. 3. Mark the packages box you want to install, that is MYSQL client and server 4. Click on Apply to begin the installation. In middle of installation you will have to enter root password for MySQL server. Enter a strong password for that. 5. We can also install MYSQL using the command #apt-get install mysql-server and #apt-get install mysql-client 6. MySQL initially only allows connections from the localhost (127.0.0.1). To remove this restriction and to make it accessible to everyone on the internet, open the file /etc/mysql/my.cnf using the command #vi /etc/mysql/my.cnf Find the line bind-address = 127.0.0.1 and comment it out, like this #bind-address = 127.0.0.1 7. We can check our configuration using the following command #netstat -tap

University Register No:

111

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Output Looks like tcp 0 0 *:mysql *:* LISTEN 4997/mysqld 8. To access MYSQL server you can use following command in the linux terminal. mysql -u root -p. Then enter the root password that you entered at the time of installation. 9. Now we can create and use databases, tables..etc. CREATING AND USING DATABASES It involves:

Create a database Create a table Load data into the table Retrieve data from the table in various ways - A database can be created using the following command CREATE DATABASE database_name; Database names are case sensitive. It should be specified in small letters. -To access an existing database the following command is used. USE database_name; -To create tables in a database the following command is used CREATE TABLE table_name(column_name1 Datatype, column_name2 Datatype ); Table names are also case sensitive. It should be specified in small letters. -To insert data into a table the following command is used INSERT INTO table_nameVALUES(value1, value2,.); -To Select all data from a table SELECT * FROM table_name; -To select particular rows SELECT * FROM table_name WHERE conditions; -To select particular columns SELECT column_name1, column_name2 FROM table_name; -To sort rows SELECT * FROM table_name ORDER BY condition; -To delete all data from the table
University Register No:

112

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

DELETE FROM table_name; -To delete data according to a condition DELETE FROM table_name WHERE condition; -We can perform various operations by using different commands as in SQL. Above mentioned are some of the important commands.

CONCLUSION: MySQL is installed; Mentioned familiarization experiments were successfully completed.

University Register No:

113

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 10 Date: 10-12-2012 IMPLEMENTATION WEBMIN OF REMOTE SYSTEM ADMINISTRATION USING

PROBLEM DEFINITION Implementation of Remote System Administration Using Webmin THEORETICAL BACKGROUND

INTRODUCTION TO WEBMIN Webmin is a program that simplifies the process of managing a Linux or UNIX system. Traditionally, you have needed to manually edit configuration files and run commands to create accounts, set up web servers, or manage email forwarding. Webmin now lets you perform these tasks through an easy-to-use web interface, and automatically updates all of the required configuration files for you. This makes the job of administering your system much easier. Some of the things that you can do with Webmin include: Creating, editing, and deleting UNIX login accounts on your system Exporting files and directories to other systems with the NFS protocol Setting up disk quotas to control how much space users can take up with their files Installing, viewing, and removing software packages in RPM and other formats Changing your system's IP address, DNS settings, and routing configuration Setting up a firewall to protect your computer or give hosts on an internal LAN access to the Internet

University Register No:

114

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Creating and configuring virtual web sites for the Apache Web server Managing databases, tables, and fields in a MySQL or PostgreSQL database server Sharing files with Windows systems by configuring Samba These are just a few of the available functions. Webmin lets you configure almost all of the common services and popular servers on UNIX systems using a simple web interface. It protects you from the syntax errors and other mistakes that are often made when editing configuration files directly, and warns you before potentially dangerous actions. Because Webmin is accessed though a web browser, you can log in to it from any system that is connected to yours through a network. There is absolutely no difference between running it locally and running it remotely, and it is much easier to use over the network than other graphical configuration programs. Webmin has what is known as a modular design. This means that each of its functions is contained in a module that can generally be installed or removed independently from the rest of the program. Each module is responsible for managing some service or server, such as UNIX users, the Apache Web server, or software packages. If you have been manually configuring your system up till now, any existing settings will be recognized by Webmin. It always reads the standard configuration files on your system and updates them directly, instead of using its own separate database. This means that you can freely mix Webmin, manual configuration, and other programs or scripts that work in the same way. Webmin can be used on many other flavors of UNIX as well, such as Solaris, FreeBSD, and HP/UX. One of its biggest strengths is its understanding of the differences between all these operating systems and the way it adjusts its user interface and behavior to fit your OS. This means that it can often hide the underlying differences between each UNIX variant and present a similar or identical interface no matter which one you are using. Webmin on its own is not particularly useful thoughit is only a configuration tool, so you must have programs installed for it to configure. For example, the Apache module requires that the actual Apache Web server be installed. Fortunately, all of the services and servers that Webmin manages are either included with most Linux distributions as standard, or can be freely downloaded and installed. It is a web-based system configuration tool for Unix-like systems, although recent
University Register No:

115

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

versions can also be installed and run on Windows. With it, it is possible to configure operating system internals, such as users, disk quotas, services or configuration files, as well as modify and control open source apps, such as the Apache HTTP Server, PHP or MySQL. Webmin is largely based on Perl, running as its own process and web server. It defaults to TCP port 10000 for communicating, and can be configured to use SSL if OpenSSL is installed with additional required Perl Modules. It is built around modules, which have an interface to the configuration files and the Webmin server. This makes it easy to add new functionality. Due to Webmin's modular design, it is possible for anyone who is interested to write plugins for desktop configuration. Webmin also allows for controlling many machines through a single interface, or seamless login on other webmin hosts on the same subnet or LAN. Webmin is primarily coded by Australian Jamie Cameron and released under the BSD license.

PROGRAM DEVELOPMENT STEPS: DOWNLOAD 1. If you are using the DEB version of webmin run the command on a terminal for downloading the packages : wget http://prdownloads.sourceforge.net/webadmin/webmin_1.610_all.deb INSTALLING 1. For installing run the command : dpkg --install webmin_1.610_all.deb If Debian complains about missing dependencies, you can install them with the command : apt-get install perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-ptyperl apt-show-versions python If you are installing on Ubuntu and the apt-get command reports that some of the packages
University Register No:

116

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

cannot be found, edit /etc/apt/sources.list and make sure the lines ending with universe are not commented out. Some Debian-based distributions (Ubuntu in particular) don't allow logins by the root user by default. However, the user created at system installation time can use sudo to switch to root. Webmin will allow any user who has this sudo capability to login with full root privileges. 2. The install will be done automatically to /usr/share/webmin, the administration username set to root and the password to your current root password. You should now be able to login to Webmin at the URL http://localhost:10000/. Or if accessing it remotely, replace localhost with your system's IP address.

CONCLUSION Webmin tool is installed, Mentioned familiarization experiments were successfully completed.

University Register No:

117

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Socket programming in C

University Register No:

118

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No : 1 Date : 12-10-2012

TCP
PROBLEM DEFINITION Implement TCP Server and TCP Client to send a word THEORETICAL BACKGROUND TCP, a connection-oriented stream protocol in which communication happens using a handshake process, where each data that is sent is acknowledged by the recipient within the time of TCP timer value. TCP provides many services such as data reliability, error checking, and flow control. If a data packet is corrupt or lost (not acknowledged), TCP will retransmitted the data from the client side automatically. Because the route a packet takes can be many, one packet may arrive before the one sent earlier. As data packets arrive, it is the job of TCP to assemble the packets into the proper order. Benefits of using TCP over UDP are: Good failure recovery The ability to add networks without interrupting existing services High error-rate handling Platform independence Low data overhead

There are 2 processes. A client process P1 and a server process P2. P1 and P2 may be in 2 different computer systems connected across a network. P1 establishes a connection with process P2 using TCP protocol. The client P1 reads a filename from the user. It sends the file name to server P2. P2 reads the contents of the file from the system and sends the contents to P1. P1 in turn displays the contents to the user.

The basic steps in socket programming are: 1. socket() creates a new socket of a certain socket type, identified by an integer number, and allocates system resources to it. 2. bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local port number and IP address.
University Register No:

119

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

3. listen() is used on the server side, and causes a bound TCP socket to enter listening state. 4. connect() is used on the client side, and assigns a free local port number to a socket. In case of a TCP socket, it causes an attempt to establish a new TCP connection. 5. accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection. 6. send() and recv(), or write() and read(), or sendto() and recvfrom(), are used for sending and receiving data to/from a remote socket. 7. close() causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated.

ALGORITHM: Server Step 1: Start Step 2: Open the server socket. Step 3: Accept the connection from the client. Step 4: Client send message to the server Step 5: Display the contents. Step 6: Send message to client. Step 7: Stop the server connection or close server socket using close(). Client Step 1: Start. Step 2: Open the client socket at port. Step 3: Establish the connection with the server machine. Step 4: Enter the message Step 5: Send message to the server socket. Step 6: Display the contents. Step 7: Stop the client connection or close client socket using close(). PROGRAM DEVELOPMENT client #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h>
University Register No:

120

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

#include <errno.h> #include <arpa/inet.h> int main(int argc,char *argv[]) { int client_sock_id,connect_id; struct sockaddr_in serv_addr; //Declaring server socket adress for sever struct hostent *host; client_sock_id=socket(AF_INET,SOCK_STREAM,0);

host = gethostbyname("127.0.0.1"); serv_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(serv_addr.sin_zero),8); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(9234); while(1) { connect_id=connect(client_sock_id,(struct sockaddr *) & serv_addr,sizeof

(serv_addr)); if(connect_id==0) { printf("Client connection estalished\n"); } } }

Server: . #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> int main(int argc,int *argv[])
University Register No:

121

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

{ int serv_sock_id,accept_id; struct sockaddr_in serv_addr,client_addr; serv_sock_id=socket(AF_INET,SOCK_STREAM,0); memset(&serv_addr,'0',sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); serv_addr.sin_port=htons(9234);

int i=bind(serv_sock_id,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); listen(serv_sock_id,20); int sizelen=sizeof(client_addr); while(1) { accept_id=accept(serv_sock_id,(struct sockaddr*)&client_addr,&sizelen); if(accept_id>=0) printf("Connection established\n"); } }

SUMMARY OF RESULT Server: ./server Connection established Client : ./client

CONCLUSION The program was implemented successfully and output is obtained.

University Register No:

122

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No : 2 Date : 19-10-2012

UDP
PROBLEM DEFINITION Implement UDP Server and UDP Client to send a word THEORETICAL BACKGROUND The User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768. UDP uses a simple transmission model with a minimum of protocol mechanism.[1] It has no handshaking dialogues, and thus exposes any unreliability of the underlying network protocol to the user's program. As this is normally IP over unreliable media, there is no guarantee of delivery, ordering or duplicate protection. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. UDP is suitable for purposes where error checking and correction is either not necessary or performed in the application, avoiding the overhead of such processing at the network interface level. Time-sensitive applications often use UDP because dropping packets is preferable to waiting for delayed packets, which may not be an option in a real-time system.[2] If error correction facilities are needed at the network interface level, an application may use the Transmission Control Protocol (TCP) or Stream Control Transmission Protocol (SCTP) which are designed for this purpose. A number of UDP's attributes make it especially suited for certain applications.

It is transaction-oriented, suitable for simple query-response protocols such as the Domain Name System or the Network Time Protocol.

It provides datagrams, suitable for modeling other protocols such as in IP


123

University Register No:

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

tunneling or Remote Procedure Call and the Network File System.

It is simple, suitable for bootstrapping or other purposes without a full protocol stack, such as the DHCP and Trivial File Transfer Protocol.

It is stateless, suitable for very large numbers of clients, such as in streaming media applications for example IPTV

The lack of retransmission delays makes it suitable for real-time applications such as Voice over IP, online games, and many protocols built on top of the Real Time Streaming Protocol.

Works well in unidirectional communication, suitable for broadcast information such as in many kinds of service discovery and shared information such as broadcast time or Routing Information Protocol

The basic steps in socket programming are: 1.socket() creates a new socket of a certain socket type, identified by an integer number, and allocates system resources to it. 2.bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local port number and IP address. 3.listen() is used on the server side, and causes a bound TCP socket to enter listening state. 4.connect() is used on the client side, and assigns a free local port number to a socket. In case of a TCP socket, it causes an attempt to establish a new TCP connection. 5.accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection. 6.send() and recv(), or write() and read(), or sendto() and recvfrom(), are used for sending and receiving data to/from a remote socket. 7.close() causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated. ALGORITHM: Server Step 1: Start Step 2: Open the server socket. Step 3: Accept the connection from the client. Step 4: Client send message to the server Step 5: Display the contents.
University Register No:

124

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Step 6: Send message to client. Step 7: Stop the server connection or close server socket using close(). Client Step 1: Start. Step 2: Open the client socket at port. Step 3: Establish the connection with the server machine. Step 4: Enter the message Step 5: Send message to the server socket. Step 6: Display the contents. Step 7: Stop the client connection or close client socket using close(). PROGRAM DEVELOPMENT client #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> int main(int argc,char *argv[]) { int client_sock_id,connect_id; char buff[50]="Hello"; struct sockaddr_in serv_addr; struct hostent *host; client_sock_id=socket(AF_INET,SOCK_DGRAM,0); host = gethostbyname("127.0.0.1"); serv_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(serv_addr.sin_zero),8); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(8257); sendto(client_sock_id,buff,sizeof(buff),0,(struct sockaddr *) &serv_addr,sizeof(serv_addr)); }

Server: #include <sys/socket.h> #include <netinet/in.h>


University Register No:

125

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

#include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> int main(int argc,int *argv[]) { int serv_sock_id,accept_id; char buff[20]; struct sockaddr_in serv_addr,client_addr serv_sock_id=socket(AF_INET,SOCK_DGRAM,0); memset(&serv_addr,'0',sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); serv_addr.sin_port=htons(8257); int i=bind(serv_sock_id,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); printf("i=%d",i);

listen(serv_sock_id,20); int sizelen=sizeof(client_addr); recvfrom(serv_sock_id,buff,sizeof(buff),0,(struct sockaddr *)&client_addr,&sizelen); printf("The recieved message=%s\n",buff); } SUMMARY OF RESULT Server: ./server Hello Client : ./client CONCLUSION The program was implemented successfully and output is obtained.

University Register No:

126

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 3 Date: 26/10/2012

DATE AND TIME SERVER


PROBLEM DEFINITION Design the date and time server to obtain the system date and time as requested by the client. THEORETICAL BACKGROUND A socket is an end point of communication between two systems on a network. To be a bit precise, a socket is a combination of IP address and port on one system. So on each system a socket exists for a process interacting with the socket on other system over the network. A combination of local socket and the socket at the remote system is also known a Four tuple or 4-tuple. Each connection between two processes running at different systems can be uniquely identified through their 4-tuple.Sockets can be used in many languages like Java, C++ etc .We will understand the socket communication in its purest form (i.e in C programming language) Lets create a server that continuously runs and sends the date and time depends upon the client request. Here we implemented the date and time socket program using TCP.Here we are including one additional header file time.h. The gettimeofday() is used to Get actual time, resolution 0.01 seconds and strftime() places bytes into the array pointed. time_t type for simple times i.e, Is exactly identical to "int" in behaviour. You may assign int values to a time_t variable, and vice-versa, and print time_t values using the %d format, The timeval struct used to measure time has only two fields, and both are unsigned ints. They are named tv_sec and tv_usec, and jointly represent one single value.

ALGORITHM: Server Step 1: Start Step 2: Create server socket and accept client. Step 3: Receive the input (i.e. DATE/TIME) from the client and process it. Step 4: Get time &date using gettimeofday() and write it to arrays like date1 & time1 Step 5: Send the contents to client.
University Register No:

127

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Step 6: Close the socket and stop. Client Step 1: Start. Step 2: Create a client side socket with server address.. Step 3: Establish the connection with the server machine. Step 4: Send date or time request to server. (i.e. DATE/TIME) through the socket.. Step 5: Display the contents received from the server and point the result. Step 6: Close the socket and stop.

PROGRAM DEVELOPMENT Server program:#include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/time.h> #include<time.h> #include<errno.h> int main(int argc,char *argv[]) { int sock,connected,sin_size,n,portno; char buff[255],time1[30],date1[30]; struct sockaddr_in servadd,cliadd; struct timeval tv; time_t curtime; if(argc<2) printf("portnumber is not defined"); gettimeofday(&tv, NULL); //Get time and date curtime=tv.tv_sec; strftime(date1,30,"%m-%d-%Y ",localtime(&curtime));//date details in date1 strftime(time1,30,"%T ",localtime(&curtime));//time details in time1 sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) perror("socket failed"); bzero((char*) &servadd,sizeof(servadd)); servadd.sin_family=AF_INET; servadd.sin_addr.s_addr=INADDR_ANY; portno=atoi(argv[1]); servadd.sin_port=htons(portno); if(bind(sock,(struct sockaddr *)&servadd,sizeof(servadd))<0) perror("binding fialed");
University Register No:

128

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

listen(sock,5); sin_size=sizeof(cliadd); connected=accept(sock,(struct sockaddr *)&cliadd,&sin_size); if(connected<0) perror("accept failed"); while(1) { bzero(buff,255); n=read(connected,buff,255); if(n<0) printf("reading error"); if(strcmp(buff,"exit\n")==0) { write(connected,"exit",4); exit(0); } else if(strcmp(buff,"TIME")==0) { n=write(connected,time1,strlen(time1)); if(n<0) error("writing failed"); } else if(strcmp(buff,"DATE")==0) { n=write(connected,date1,strlen(date1)); if(n<0) error("writing failed"); } else { printf("\n%s",buff); n=write(connected,buff,255); } } close(connected); close(sock); return 0; }

Client program:#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #include<string.h> #include<netdb.h> #include<stdlib.h> #include<netinet/in.h> #include<errno.h> int main(int argc,char *argv[])
University Register No:

129

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

{ int sock,portno,n; char buffer[255]; struct sockaddr_in servaddr; struct hostent *server; if(argc<4) { printf("Enter host name, port number, DATE or TIME"); } sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) error("socket error"); server=gethostbyname(argv[1]); if(server==NULL) printf("\nHost not found"); bzero((char*)&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; portno=atoi(argv[2]); servaddr.sin_port=htons(portno); if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) error("connection failed"); strcpy(buffer,argv[3]); if(strcmp(buffer,"TIME")==0) { n=write(sock,buffer,strlen(buffer)); if(n<0) perror("writing is failed"); } else if(strcmp(buffer,"DATE")==0) { n=write(sock,buffer,strlen(buffer)); if(n<0) printf("\nwriting is failed"); } else { printf ("plz enter in format ./cli localhost portnumber TIME/DATE"); } bzero(buffer,255); n=read(sock,buffer,255); printf("\nOUTPUT:%s\n",buffer); if(n<0) printf("\nreading is failed"); while(1) { bzero(buffer,255); fgets(buffer,255,stdin); n=write(sock,buffer,strlen(buffer)); if(n<0) error("writing is failed"); bzero(buffer,255);
University Register No:

130

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

n=read(sock,buffer,255); if(n<0) error("reading is failed"); if(strcmp(buffer,"exit")==0) exit(0); printf("%s\n",buffer); } close(sock); return 0; }

SUMMARY OF RESULT Client gcc o cli client.c


./cli localhost 5000 DATE OUTPUT:01-21-2013 ./cli localhost 5000 TIME OUTPUT:09:09:18

Server gcc o ser client.c


./ser 5000

CONCLUSION The date and time server using tcp was successfully implemented and desired output is obtained.

University Register No:

131

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No : 4 Date : 2-11-2012

Multicasting
PROBLEM DEFINITION Implementing multi-cast client server application to multiple clients. THEORETICAL BACKGROUND Multicast communication gives the application programmer the ability to open a UDP socket and send a packetized chunk of data once. And yet the packet is delivered to potentially many receivers. Instead of sending N separate but identical packets to each of N receivers, one multicast packet can be sent that will reach all N receivers, even if N is large. A special range of IP addresses is used to create a logical group of receivers. Using this address, the application programmer has the ability to send one or a stream of packets to this destination address and expect the network to attempt to deliver a copy of the packet to each receiver in the multicast group. Multicast communication relies on additional functionality in the network to build a "multicast forwarding tree" between the sending application and the group of receivers. The concept of a tree is an accurate one. The source is located at the "root" of the tree. From the root, a packet stream flows up the trunk to "branches." At each branch in the tree, the network receives an incoming packet and copies it to each of the outgoing branches. The functionality necessary to build and maintain multicast trees for a group of receivers is slowly being deployed throughout the Internet. Deployment means that additional function-ality, using additional software a n d / o r hardware, is being deployed in Internet switches and routers as well as in host operating systems and applications. Deployment also means that there are programmers who are using multicast as an effective technique in building large-scale distributed applications. For an application programmer, using multicast means understanding the syntactic changes to the socket Application Programming Interface (API) as well as understanding the implications of using such a powerful communication mechanism. ALGORITHM Server Step 1: Create a socket. Step 2: Optionally set the port reuse socket option. 3: Bind to the socket. 4: Join the multicast group.
University Register No:

132

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

5: Receive multicast data. 6: Drop the multicast group. 7:Close the socket. Client Step 1 : Start Step 2 : Create a socket using socket (). Step3: Set the TTL using setsockopt () (optional). Step4: Send data using sendto(). Step5: Close the socket using close(). PROGRAM DEVELOPMENT Server #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #define HELLO_PORT 12345 #define HELLO_GROUP "225.0.0.37" main(int argc, char *argv[]) { struct sockaddr_in addr; int sock; struct ip_mreq mreq; char *message="Hello"; /* create what looks like an ordinary UDP socket */ if ((sock=socket(AF_INET,SOCK_DGRAM,0)) < 0) { perror("socket"); exit(1); } /* set up destination address */
University Register No:

133

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

addr.sin_family=AF_INET; addr.sin_addr.s_addr=inet_addr(HELLO_GROUP); addr.sin_port=htons(HELLO_PORT); bzero(&(addr.sin_zero),8); /* now just sendto() our destination! */ while (1) { if (sendto(sock,message,sizeof(message),0,(struct sockaddr *) &addr,sizeof(addr)) < 0) { perror("sendto"); exit(1); } sleep(1); } }

Client #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #define HELLO_PORT 12345 #define HELLO_GROUP "225.0.0.37" #define MSGBUFSIZE 6 main(int argc, char *argv[]) { struct sockaddr_in addr; int sock, nbytes,addrlen; struct ip_mreq mreq; char msgbuf[MSGBUFSIZE];
University Register No:

134

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

u_int yes=1; /* create what looks like an ordinary UDP socket */ if ((sock=socket(AF_INET,SOCK_DGRAM,0)) < 0) { perror("socket"); exit(1); } /* allow multiple sockets to use the same PORT number */ /* if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) < 0) { perror("Reusing ADDR failed"); exit(1); } /* set up destination address */ //memset(&addr,0,sizeof(addr)); addr.sin_family=AF_INET; addr.sin_addr.s_addr=htonl(INADDR_ANY); /* N.B.: differs from sender */ addr.sin_port=htons(HELLO_PORT); bzero(&(addr.sin_zero),8); /* bind to receive address */ if (bind(sock,(struct sockaddr *) &addr,sizeof(addr)) < 0) { perror("bind"); exit(1); } /* use setsockopt() to request that the kernel join a multicast group */ mreq.imr_multiaddr.s_addr=inet_addr(HELLO_GROUP); mreq.imr_interface.s_addr=htonl(INADDR_ANY); if (setsockopt(sock,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq)) < 0) { perror("setsockopt"); exit(1); } /* now just enter a read-print loop */
University Register No:

135

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

while (1) { addrlen=sizeof(addr); if ((nbytes=recvfrom(sock,msgbuf,MSGBUFSIZE,0, (struct sockaddr *) &addr,&addrlen)) < 0) { perror("recvfrom"); exit(1); } puts(msgbuf); } }

SUMMARY RESULT Server: ./server Client : ./client Hello Hello Hello

CONCLUSION The program to implement multi-cast to multiple clients was implemented successfully and output is obtained.

University Register No:

136

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 5 Date: 16-11-2012 IMPLEMENT BROADCAST PROBLEM DEFINITION Implement broadcast

THEORETICAL BACKGROUND Broadcasting refers to a method of transferring a message to all recipients simultaneously. Broadcasting can be performed as a high level operation in a program, for example broadcasting Message Passing Interface or it may be a low level networking operation, for example broadcasting on Ethernet. In computer networking, broadcasting refers to

transmitting a packet that will be received by every device on the network. In practice, the scope of the broadcast is limited to a broadcast domain. Broadcast a message is in contrast to unicast addressing in which a host sends datagrams to another single host identified by a unique IP address. Not all network technologies support broadcast addressing; for example, neither X.25 nor frame relay have broadcast capability, nor is there any form of Internet-wide broadcast. Broadcasting is largely confined to local area network (LAN) technologies, most notably Ethernet and token ring, where the performance impact of broadcasting is not as large as it would be in a wide area network. The successor to Internet Protocol Version 4 (IPv4), IPv6 also does not implement the broadcast method, so as to prevent disturbing all nodes in a network when only a few may be interested in a particular service. Instead it relies on multicast addressing a conceptually similar one-to-many routing methodology. However, multicasting limits the pool of receivers to those that join a specific multicast receiver group. Both Ethernet and IPv4 use an all-ones broadcast address to indicate a broadcast packet. Token Ring uses a special value in the IEEE 802.2 control field. Broadcasting may be abused to perform a DoS-attack. The attacker sends fake ping request with the source IP-address of the victim computer. The victim computer is flooded by the replies from all computers in the domain.

University Register No:

137

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

ALGORITHM: Sender Step 1: Declare the variables for creating socket and broadcasting Step 2: Initialize the broadcast IP ,Port and Sending string variables using the arguments passed Step 3: Create the socket using socket function. Step 4: Set the broadcast permission variable as 1 and set the socket option (set the state of socket). setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission)) < 0 Step 5: Construct local address structure or attach details to socket created. broadcastAddr.sin_family = AF_INET; broadcastAddr.sin_addr.s_addr = inet_addr(broadcastIP); broadcastAddr.sin_port = htons(broadcastPort); Step 6: Send the string to the destination addresses using sendto function sendto(sock, sendString, sendStringLen, 0, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) != sendStringLen Step 7.:After a time interval send the data again.

Receiver Step 1: Declare the variables for creating socket and String receiving buffer Step 2: Initialize the broadcast IP ,Port variables using the arguments passed Step 3: Create the socket using socket function. Step 4: Construct local address structure or attach details to socket created. broadcastAddr.sin_family = AF_INET; broadcastAddr.sin_addr.s_addr = inet_addr(broadcastIP); broadcastAddr.sin_port = htons(broadcastPort); Step 5:Bind the socket with address. bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) ;

PROGRAM DEVELOPMENT Sender #include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket() and bind() */ #include <arpa/inet.h> /* for sockaddr_in */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */

University Register No:

138

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

void DieWithError(char *errorMessage) { perror(errorMessage); exit(1); } /* External error handling function */ int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in broadcastAddr; /* Broadcast address */ char *broadcastIP; /* IP broadcast address */ unsigned short broadcastPort; /* Server port */ char *sendString; /* String to broadcast */ int broadcastPermission; /* Socket opt to set permission to broadcast */ unsigned int sendStringLen; /* Length of string to broadcast */ if (argc < 4) /* Test for correct number of parameters */ { fprintf(stderr,"Usage: %s <IP Address> <Port> <Send String>\n", argv[0]); exit(1); } broadcastIP = argv[1]; /* First arg: broadcast IP address */ broadcastPort = atoi(argv[2]); /* Second arg: broadcast port */ sendString = argv[3]; /* Third arg: string to broadcast */ /* Create socket for sending/receiving datagrams */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Set socket to allow broadcast */ broadcastPermission = 1; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission)) < 0) DieWithError("setsockopt() failed"); /* Construct local address structure */ memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */ broadcastAddr.sin_family = AF_INET; /* Internet address family */ broadcastAddr.sin_addr.s_addr = inet_addr(broadcastIP);/* Broadcast IP address */ broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */ sendStringLen = strlen(sendString); /* Find length of sendString */ for (;;) /* Run forever */ { /* Broadcast sendString in datagram to clients every 3 seconds*/ if (sendto(sock, sendString, sendStringLen, 0, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) != sendStringLen)
University Register No:

139

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

DieWithError("sendto() sent a different number of bytes than expected"); sleep(3); /* Avoids flooding the network */ } /* NOT REACHED */ }

Receiver #include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket(), connect(), sendto(), and recvfrom() */ #include <arpa/inet.h> /* for sockaddr_in and inet_addr() */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #define MAXRECVSTRING 255 /* Longest string to receive */ //void DieWithError(char *errorMessage); /* External error handling function */ int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in broadcastAddr; /* Broadcast Address */ unsigned short broadcastPort; /* Port */ char recvString[MAXRECVSTRING+1]; /* Buffer for received string */ int recvStringLen; /* Length of received string */ if (argc != 2) /* Test for correct number of arguments */ { fprintf(stderr,"Usage: %s <Broadcast Port>\n", argv[0]); exit(1); } broadcastPort = atoi(argv[1]); /* First arg: broadcast port */ /* Create a best-effort datagram socket using UDP */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) printf("socket() failed"); /* Construct bind structure */ memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */ broadcastAddr.sin_family = AF_INET; /* Internet address family */ broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */ /* Bind to the broadcast port */ if (bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) < 0)
University Register No:

140

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

printf("bind() failed"); /* Receive a single datagram from the server */ while(1) { bzero(recvString,256); if ((recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0) printf("recvfrom() failed"); recvString[recvStringLen] = '\0'; printf("Received: %s\n", recvString); //close(sock); //exit(0); } }

/* Print the received string */

SUMMARY OF RESULT Server: ./server 225.0.0.37 4992 Hello Client: ./client 4992 Hello Hello Hello

CONCLUSION Connection was established between the server and the client. Broadcast sendString in datagram to clients and then receive a single datagram from the server. Thus broadcast was successfully implemented.

University Register No:

141

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 6 Date: 30-11-2012

FILE TRANSFER USING TCP


PROBLEM DEFINITION Design TCP client and server application to transfer file. THEORETICAL BACKGROUND TCP, a connection-oriented stream protocol in which communication happens using a handshake process, where each data that is sent is acknowledged by the recipient within the time of TCP timer value. TCP provides many services such as data reliability, error checking, and flow control. If a data packet is corrupt or lost (not acknowledged), TCP will retransmitted the data from the client side automatically. Because the route a packet takes can be many, one packet may arrive before the one sent earlier. As data packets arrive, it is the job of TCP to assemble the packets into the proper order. Benefits of using TCP over UDP are: Good failure recovery The ability to add networks without interrupting existing services High error-rate handling Platform independence Low data overhead There are 2 processes. A client process P1 and a server process P2. P1 and P2 may be in 2 different computer systems connected across a network. P1 establishes a connection with process P2 using TCP protocol. The client P1 reads a filename from the user. It sends the file name to server P2. P2 reads the contents of the file from the system and sends the contents to P1. P1 in turn displays the contents to the user. The basic steps in socket programming are: 8. socket() creates a new socket of a certain socket type, identified by an integer number, and allocates system resources to it. 9. bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local port number and IP address. 10. listen() is used on the server side, and causes a bound TCP socket to enter listening state. 11. connect() is used on the client side, and assigns a free local port number to a socket. In case of a TCP socket, it causes an attempt to establish a new TCP connection. 12. accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection. 13. send() and recv(), or write() and read(), or sendto() and recvfrom(), are used for sending and receiving data to/from a remote socket. 14. close() causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated.
University Register No:

142

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

ALGORITHM: Server Step 1: Start Step 2: Open the server socket. Step 3: Accept the connection from the client. Step 4: Get the File name from the client and read the contents from it. Step 5: Display the contents. Step 6: Send the contents to client. Step 7: Stop the server connection or close server socket using close(). Client Step 1: Start. Step 2: Open the client socket at port. Step 3: Establish the connection with the server machine. Step 4: Enter the File name. Step 5: Send the File name to the server socket. Step 6: Display the contents. Step 7: Stop the client connection or close client socket using close().

PROGRAM DEVELOPMENT Server side #include<stdio.h> #include<fcntl.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<strings.h> main() { int serversockfd, newserversockfd, clilen, n, rc, f; char line[100],fline[300]; struct sockaddr_in clientaddr, serveraddr; fflush(stdin); serversockfd = socket( AF_INET, SOCK_STREAM, 0); /* set the address details of server socket*/ bzero( (char *)&serveraddr, sizeof( serveraddr) ); serveraddr. sin_family=AF_INET; serveraddr. sin_addr. s_addr=htonl(INADDR_ANY); serveraddr. sin_port = htons(3000); bind(serversockfd, (struct sockaddr *)&serveraddr, sizeof( serveraddr) ); /* listen for the connection*/ listen( serversockfd, 5); while(1) {
University Register No:

143

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

clilen = sizeof( clientaddr); /* accept the connectionfrom the client */ newserversockfd = accept(serversockfd, (struct sockaddr *)&clientaddr, &clilen); n = read(newserversockfd, line, 100); line[n]=0; printf("\n The requested file name from the client is\t\t%s",line); write(1,line,n); printf("\n"); /* open the file and access the data or content*/ f=open( line, O_RDWR ); n=read(f,fline,300); printf("\nThe contents of the file are\n\n"); printf("%s",fline); write( newserversockfd, fline, n); } close(serversockfd); close(newserversockfd); } Client side #include<stdio.h> #include<netdb.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<stdlib.h> #include<strings.h> #include<string.h> main() { int clientsockfd, n, nleft, nwritten, c, rc; char sendline[20], recvline[300]; struct sockaddr_in serveraddr; /* set the address details of the remote server socket*/ bzero( (char *)&serveraddr, sizeof(serveraddr) ); serveraddr. sin_family = AF_INET; serveraddr. sin_addr. s_addr=htonl(INADDR_ANY); serveraddr. sin_port = htons(3000); clientsockfd =socket(AF_INET,SOCK_STREAM,0); if(connect(clientsockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))<0 ) { printf("\nCannot Connect"); exit(0); } printf("\nEnter the name of a file at the server\t"); scanf("%s",sendline); n=strlen(sendline);
University Register No:

144

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

write( clientsockfd, sendline, n); rc = read( clientsockfd, recvline, 300); printf("\nThe contents of the file at the server are\n\n"); printf("%s",recvline); close(clientsockfd); }

SUMMARY OF RESULT (Client) Enter the name of file at server: hi.c The contents of the file at the server are hello (Server) The requested file name from the client is hi.c The contents of the file are hello CONCLUSION Thus file transfer using TCP was successfully implemented.

University Register No:

145

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No :7 Date : 7-11-2012

Client server application to multiplex TCP and UDP requests for converting a given text into upper case a. using select() b. using poll()
PROBLEM DEFINITION Design using poll client server application to multiplex TCP and UDP requests for converting a given text into upper case

THEORETICAL BACKGROUND The select() and poll() methods can be a powerful tool when youre multiplexing network sockets. Specifically, these methods will indicate when a procedure will be safe to execute on an open file descriptor without any delays. For instance, a programmer can use these calls to know when there is data to be read on a socket. By delegating responsibility to select() and poll(), you dont have to constantly check whether there is data to be read. Instead, select() and poll() can be placed in the background by the operating system and woken up when the event is satisfied or a specified timeout has elapsed. This process can significantly increase execution efficiency of a program. select( ) description The Single UNIX Specification, version 2 (SUSv2) defines select() as follows: int select(intnfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, structtimeval*timeout); It takes these parameters: intnfds- The highest file descriptor in all given sets plus one fd_set *readfds- File descriptors that will trigger a return when data is ready to be read fd_set *writefds- File descriptors that will trigger a return when data is ready to be written to fd_set *errorfds- File descriptors that will trigger a return when an exception occurs structtimeval *timeout - The maximum period select() should wait for an event The return value indicates the number of file descriptors (fds) whose request event has been satisfied.You cant modify the fd_set structure by changing its value directly. poll() description
University Register No:

146

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

The poll() method attempts to consolidate the arguments of select() and provides notification of a wider range of events. The SUSv2 defines poll() as follows:

int poll(structpollfdfds[ ], nfds_tnfds, int timeout); It takes these parameters: structpollfdfds[ ] - An array ofpollfdstructures nfds_tnfds- The number of file descriptors set infds[ ] int timeout - How long poll() should wait for an event to occur (in milliseconds) The return value indicates how many fds had an event occur. A pollfdstruct typically includes the following members: intfd- Indicates which fd to monitor for an event short events - A bitwise field that represents which events will be monitored shortrevents- A bitwise field that represents which events were detected in a call to poll()

ALGORITHM

Server Step 1 : start Step 2 : create socket at server side, bind and listen for any connection from client side Step 3: Polling is performed by getting the client request each time from the buffer and response is send back. Here the lowercasetext or input string sent by client is converted every time into uppercase at server side using ASCII value of each alphabets by fetching data from buffer. This can be done for any number of clients .if any error, connection is reset by the client. Step 4 : Stop the server connection or close server socket using close().

Client Step 1: start Step 2: create a socket at client side for communication with server. Step 3: socket cannot be created if its a negative value Step 4: set the buffer or clear the buffer initially using memset().The client sends a lowercase text or input string to be converted into uppercase at server . Step 5: Stop the client connection or close client socket using close().
University Register No:

147

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

PROGRAM DEVELOPMENT Using Poll() Client side #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h>

#define MAXBUFFER 1024 voidsendstring(int , char *); int main( int C, char *V[] ) { structsockaddr_inserveraddress; intsock_desc,i=0; charc,text[100],rec[20]; //Creating Socket sock_desc = socket( AF_INET, SOCK_STREAM, 0 ); if(sock_desc< 0 ) { perror( "socket creation failed"); exit( 1 ); } //Checking the argument list for getting IP Address & Port if (V[1] == NULL ) { printf ("PL specfiy the server's IP Address \n"); exit(0); } if (V[2] == NULL ) { printf ("PL specify the server's Port No \n"); exit(0); }
University Register No:

148

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

//Initializing sockaddr_in variables serveraddress.sin_family = AF_INET; serveraddress.sin_port = htons(atoi(V[2])); serveraddress.sin_addr.s_addr = inet_addr(V[1]); //Connect to Server if (connect(sock_desc,(structsockaddr*)&serveraddress,sizeof(serveraddress))<0) { printf("Cannot Connect to server"); exit(1); } //Entering String to send to server printf("Please enter the String to send to Server. "); text[i]='\0'; send(sock_desc,text,strlen(text),0); recv(sock_desc,rec,20,0); printf(The message from the server is %s,rec); close(sock_desc); return 0; } Server side #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <limits.h> /* for OPEN_MAX */ #include <poll.h> #include <errno.h> #define MAXLINE 100 #define SERV_PORT 7777 #define POLLRDNORM 5 #define INFTIM 5 #define OPEN_MAX 5 int main(intargc, char **argv) { int k, i, maxi, sock_desc, connfd, sockfd,x,nready; ssize_t n; char line[MAXLINE]; socklen_tclilen; structpollfd client[OPEN_MAX]; structsockaddr_incliaddr, servaddr;
University Register No:

149

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

sock_desc = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); bind(sock_desc, (structsockaddr *) &servaddr, sizeof(servaddr)); listen(sock_desc, 5); client[0].fd = sock_desc; client[0].events = POLLRDNORM; for (i = 1; i < OPEN_MAX; i++) client[i].fd = -1; /* -1 indicates available entry */ maxi = 0; /* max index into client[] array */ for ( ; ; ) { nready = poll(client, maxi+1, INFTIM); if (client[0].revents& POLLRDNORM) { /* new client connection */ clilen = sizeof(cliaddr); connfd = accept(sock_desc, (structsockaddr *) &cliaddr, &clilen); #ifdef NOTDEF printf("new client: %s\n", sock_ntop((structsockaddr *) &cliaddr,clilen)); #endif for (i = 1; i < OPEN_MAX; i++) if (client[i].fd< 0) { client[i].fd = connfd; /* save descriptor */ break; } if (i == OPEN_MAX){ printf("too many clients"); exit(0); } client[i].events = POLLRDNORM; if (i > maxi) maxi = i; /* max index in client[] array */ if (--nready<= 0) continue; } for (i = 1; i <= maxi; i++) { /* check all clients for data */ if ( (sockfd = client[i].fd) < 0) continue; if (client[i].revents& (POLLRDNORM | POLLERR)) { if ( (n = read(sockfd, line, MAXLINE)) < 0) { if (errno == ECONNRESET) { /*4connection reset by client */
University Register No:

150

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

#ifdef NOTDEF printf("client[%d] aborted connection\n", i); #endif close(sockfd); client[i].fd = -1; } else printf("readline error"); } else if (n == 0) { /*4connection closed by client */ #ifdef NOTDEF printf("client[%d] closed connection\n", i); #endif close(sockfd); client[i].fd = -1; } else{printf("\n data from client is \n"); k=strlen(line); for(x=0;x<k;x++) { if(line[x]>=97&&line[x]<=122) { line[x]-=32; } } printf(" length=%d data = %s\n", k,line); strcpy(line," "); memset( line, 0, sizeof(line) ); } if (--nready<= 0) break; } } } } SUMMARY OF RESULTS Server $ ./select data from client is india data from client is bharat Client Terminal-1 $ ./ClientTCP_UpperCase
University Register No:

151

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Please enter the String to send to Server :india The message from the server is INDIA Terminal-2 $ ./ClientTCP_UpperCase Please enter the String to send to Server :bharat The message from the server is BHARAT

PROGRAM DEVELOPMENT Using Select() Client side #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h>

#define MAXBUFFER 1024

voidsendstring(int , char *); int main( int C, char *V[] ) { structsockaddr_inserveraddress; intsock_desc,i=0; charc,text[100];

//Creating Socket sock_desc = socket( AF_INET, SOCK_STREAM, 0 ); if(sock_desc< 0 ) { perror( "socket creation failed"); exit( 1 ); } //Checking the argument list for getting IP Address & Port //V[1] ->IPAddressV[2] -> Port if (V[1] == NULL )
University Register No:

152

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

{ printf ("PL specfiy the server's IP Address \n"); exit(0); } if (V[2] == NULL ) { printf ("PL specify the server's Port No \n"); exit(0); } //Initializing sockaddr_in variables serveraddress.sin_family = AF_INET; serveraddress.sin_port = htons(atoi(V[2])); serveraddress.sin_addr.s_addr = inet_addr(V[1]); //Connect to Server if (connect(sock_desc,(structsockaddr*)&serveraddress,sizeof(serveraddress))<0) { printf("Cannot Connect to server"); exit(1); } //Entering String to send to server printf("Please enter the String to send to Server. End the string with #"); while(1) { c=getchar(); if(c=='#'){ break; } else if(c==' '){ text[i++]=c; } text[i++]=c; } text[i]='\0'; sendstring(sock_desc,text); close(sock_desc); return 0; }

/* FUNCTION NAME:sendstring * DESCRIPTION: sends a string over the socket . * NOTES : No Error Checking is done . * RETURNS :void
University Register No:

153

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

*/ voidsendstring(intsock_desc,char *fname) { int n , byteswritten=0 , written ; char buffer[MAXBUFFER]; strcpy(buffer , fname); n=strlen(buffer); while (byteswritten<n) { written=write(sock_desc , buffer+byteswritten,(n-byteswritten)); byteswritten+=written; } printf("String : %s sent to server \n",buffer); } Server side #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define PORT 7777 #define MAXMSG 512 int read_from_client (intfiledes) { char buffer[MAXMSG]; intnbytes,k,x; nbytes = read (filedes, buffer, MAXMSG); if (nbytes< 0) { /* Read error. */ perror ("read"); exit (EXIT_FAILURE); } else if (nbytes == 0) /* End-of-file. */ return -1;
University Register No:

154

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

else { /* Data read. */ fprintf (stderr, "Server: got message: `%s'\n", buffer); k=strlen(buffer); for(x=0;x<k;x++) { if(buffer[x]>=97&&buffer[x]<=122) { buffer[x]-=32; } } printf(" length=%d data = %s\n", k,buffer); strcpy(buffer," "); memset( buffer, 0, sizeof(buffer) ); return 0; } } int main (void) { // extern intmake_socket(uint16_t port); int sock; fd_setactive_fd_set, read_fd_set; int i; structsockaddr_inclientname; size_t size; /* Create the socket and set it up to accept connections. */ sock = socket( AF_INET, SOCK_STREAM, 0 ); if( sock < 0 ) { perror( "socket creation failed"); exit( 1 ); } //Initializing sockaddr_in variables clientname.sin_family = AF_INET; clientname.sin_port = htons(7777); clientname.sin_addr.s_addr = htonl(INADDR_ANY); bind(sock, (structsockaddr *) &clientname, sizeof(clientname));

if (listen (sock, 1) < 0) { perror ("listen"); exit (EXIT_FAILURE); }


University Register No:

155

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

/* Initialize the set of active sockets. */ FD_ZERO (&active_fd_set); FD_SET (sock, &active_fd_set); while (1) { /* Block until input arrives on one or more active sockets. */ read_fd_set = active_fd_set; if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) { perror ("select"); exit (EXIT_FAILURE); } /* Service all the sockets with input pending. */ for (i = 0; i < FD_SETSIZE; ++i) if (FD_ISSET (i, &read_fd_set)) { if (i == sock) { /* Connection request on original socket. */ int new; size = sizeof (clientname); new = accept (sock, (structsockaddr *) &clientname, &size); if (new < 0) { perror ("accept"); exit (EXIT_FAILURE); } fprintf (stderr,"Server: connect from host %d, port %hd.\n",inet_ntoa (clientname.sin_addr), ntohs (clientname.sin_port)); FD_SET (new, &active_fd_set); } else { /* Data arriving on an already-connected socket. */ if (read_from_client (i) < 0) { close (i); FD_CLR (i, &active_fd_set); } } } } }

University Register No:

156

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

SUMMARY OF RESULTS

Server $ ./select data from client is india data from client is bharat Client Terminal-1 $ ./ClientTCP_UpperCase Please enter the String to send to Server :india The message from the server is INDIA Terminal-2 $ ./ClientTCP_UpperCase Please enter the String to send to Server :bharat The message from the server is BHARAT

CONCLUSION The program to design poll client server application and slect client server application to multiplex TCP and UDP requests for converting a given text into upper case was implemented successfully and output is obtained.

University Register No:

157

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 8 Date: 14-11-2012

ADDIND TWO NUMBERS USING RPC

PROBLEM DEFINITION

Design RPC Client and server application to add two numbers.

THEORETICAL BACKGROUND In 1984, Birrell and Nelson devised a mechanism to allow programs to call procedures on other machines. A process on machine A can call a procedure on machine B. The process on A is suspended and execution continues on B. When B returns, the return value is passed to A and A continues execution. This mechanism is called the Remote Procedure Call (RPC). To the programmer, the goal is that it should appear as if a normal procedure call is taking place. Obviously, a remote procedure call is different from a local one in the underlying implementation.

Steps in a remote procedure call Clearly, there is no architectural support for making remote procedure calls. A local procedure call generally involves placing the calling parameters on the stack and executing some form of a call instruction to the address of the procedure. The procedure can read the parameters from the stack, do its work, place the return value in a register and then return to the address on top of the stack. None of this exists for calling remote procedures. Well have to simulate it all with the tools that we do have, namely local procedure calls and sockets for network communication. This simulation makes remote procedure calls a language level construct as opposed to sockets, which are an operating system level construct. This means that our compiler will have to know that remote procedure call invocations need the presence of special code.

The entire trick in making remote procedure calls work is in the creation of stub functions
University Register No:

158

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

that make it appear to the user that the call is really local. A stub function looks like the function that the user intends to call but really contains code for sending and receiving messages over a network. The following sequence of operations takes place.

The sequence of operations, depicted in Figure, is:

1. The client calls a local procedure, called the client stub. To the client process, it appears that this is the actual procedure. The client stub packages the arguments to the remote procedure (this may involve converting them to a standard format) and builds one or more network messages. The packaging of arguments into a network message is called marshaling.

2. Network messages are sent by the client stub to the remote system (via a system call to the local kernel).

3. Network messages are transferred by the kernel to the remote system via some protocol (either connectionless or connection-oriented).

4. A server stub procedure on the server receives the messages. It unmarshals the arguments from the messages and possibly converts them from a standard form into a machine-specific form.

5. The server stub executes a local procedure call to the actual server function, passing it the arguments that it received from the client.

University Register No:

159

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

6. When the server is finished, it returns to the server stub with its return values.

7. The server stub converts the return values (if necessary) and marshals them into one or more network messages to send to the client stub.

8. Messages get sent back across the network to the client stub

9. The client stub reads the messages from the local kernel.

10. It then returns the results to the client function (possibly converting them first).

The client code then continues its execution

ALGORITHM: 1) START

2) generate the IDL file add.x //Here we will define a structure that holds two parameters. These two parameters are the input parameters of our add function. In IDL file we have to specify a number to function, version and program.

3) compile the IDL file using rpcgen >> rpcgen -C add.x

4) generate client and server code >>rpcgen -a -C add.x

//This will generate client and server codes along with some other files like the makefile.

5) compile code >> make -f makefile.add


University Register No:

160

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

6) edit makefile CC=gcc before the CFLAGS= line

//This is to change to gcc compiler.

Then CFLAGS += -g

to CFLAGS += -g DRPC_SVC_FG

//This will cause our server to run in the foreground.

Then

RPCGENFLAGS =

to RPCGENFLAGS = -C

//this is to make sure that rpcgen generates code that conforms to ANSI C.

7) Then edit the server code add_server.c to receive two parameters from the client and return the sum to the client.

8) Then edit the client code add_client.c to receive two numbers from the command line and
University Register No:

161

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

pass it to the server for addition and print the result from the server.

9) Then run ./add_server in one terminal and ./add_client localhost 1st num 2nd num in one terminal.

10) END

PROGRAM DEVELOPMENT:

IDL add.x struct intpair { int a; int b; }; program ADD_PROG { version ADD_VERS { int ADD(intpair) = 1; } = 1; } = 0x23451110;

Server /* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */

#include "add.h" int * add_1_svc(intpair *argp, struct svc_req *rqstp) { static int result;
University Register No:

162

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

printf("add function called\n"); printf("parameters: %d, %d\n", argp->a, argp->b); result = argp->a + argp->b; printf("returning: %d\n", result); return &result; }

Client /* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */

#include "add.h" #include <stdio.h>

void add_prog_1(char *host, int a, int b) { CLIENT *clnt; int *result_1; intpair add_1_arg;

#ifndef DEBUG clnt = clnt_create (host, ADD_PROG, ADD_VERS, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */
University Register No:

163

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

add_1_arg.a = a; add_1_arg.b = b;

result_1 = add_1(&add_1_arg, clnt); if (result_1 == (int *) NULL) { clnt_perror (clnt, "call failed"); } else { printf("result = %d\n", *result_1); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ }

int main (int argc, char *argv[]) {

char *host; int a, b; if (argc != 4) { printf ("usage: %s server_host num1 num2\n", argv[0]); exit(1); }

host = argv[1]; if ((a = atoi(argv[2])) == 0 && *argv[2] != '0') { fprintf(stderr, "invalid value: %s\n", argv[2]); exit(1); }

if ((b = atoi(argv[3])) == 0 && *argv[3] != '0') {


University Register No:

164

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

fprintf(stderr, "invalid value: %s\n", argv[3]); exit(1); } add_prog_1 (host, a,b); //exit (0); }

SUMMARY OF RESULT Client: >> ./add_client localhost 34 23 result = 57

Server: >>./add_server parameters: 34, 23 returning: 57

CONCLUSION: Connection was established between the server and the client. Two numbers are entered on the client side and using RPC its sum is calculated by the server and the result is returned to the client and displayed on the client. Thus addition of two numbers using RPC was successfully implemented.

University Register No:

165

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Experiment No: 9 Date: 21-11-2012


STRING REVERSE USING RPC

PROBLEM DEFINITION Design RPC program to reverse a string.

THEORETICAL BACKGROUND Remote Procedure Call (RPC) is a protocol that one program can use to request a service from a program located in another computer in a network without having to understand network details. The requesting program is a client and the service-providing program is the server. a regular or local procedure call, an RPC is a synchronous operation requiring the requesting program to be suspended until the results of the remote procedure are returned. However, the use of lightweight processes or threads that share the same address space allows multiple RPCs to be performed concurrently. When program statements that use RPC are compiled into an executable program, a stub is included in the compiled code that acts as the representative of the remote procedure code. When the program is run and the procedure call is issued, the stub receives the request and forwards it to a client runtime program in the local computer. The client runtime program has the knowledge of how to address the remote computer and server application and sends the message across the network that requests the remote procedure. Similarly, the server includes a runtime program and stub that interface with the remote procedure itself. Results are returned the same way. When an RPC is made, the calling arguments are passed to the remote procedure and the caller waits for a response to be returned from the remote procedure. The below figure shows the flow of activity that takes place during an RPC call between two networked systems. The client makes a procedure call that sends a request to the server and waits. The thread is blocked from processing until either a reply is received, or it times out. When the request arrives, the server calls a dispatch routine that performs the requested service, and sends the reply to the client.

University Register No:

166

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

In String reverse using RPC, a string is given as input to the client. Client makes a connection with the server and the forwards the string to the server. Using RPC server accepts the request, reverses the string and it is returned back to the client. A remote procedure call occurs in the following steps: The client procedure calls the client stub in the normal way. The client stub builds a message and calls the local operating system. The clients OS sends the message to the remote OS. The remote OS gives the message to the server stub. The server stub unpacks the parameters and calls the server. The server does the work and returns the result to the stub. The server stub packs it in a message and calls its local OS. The servers OS sends the message to the clients OS. The clients OS gives the message to the client stub. The stub unpacks the result and returns to the client.

University Register No:

167

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

ALGORITHM: Server Step 1: Start Step 2: Open the server socket. Step 3: Accept the connection from the client. Step 4: Get the input string from the client and reverse it. Step 5: Reversed string is passed to the client. Step 6: Stop.

Client Step 1: Start. Step 2: Open the client socket at port. Step 3: Establish the connection with the server machine. Step 4: Enter the input message. Step 5: Send the input message to the server socket. Step6: Displays the reversed string from server. Step 6: Stop. RPC Steps

* Generate the IDL file string2.x * Compile the IDL file using rpcgen - >rpcgen -C string2.x

* Generate client and server code ->rpcgen -a -C string2.x

* Compile code
>> make -f Makefile.string2

* Edit makefile

CC=gcc before the CFLAGS= line Then


University Register No:

168

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

CFLAGS += -g to CFLAGS += -g DRPC_SVC_FG

Then

RPCGENFLAGS = to RPCGENFLAGS = -C

* Then edit the server and client code like in string2_server.c and string2_client.c.

* Run ./string2_server.c in one terminal and ./string2_client.c localhost (String) in another terminal.
PROGRAM DEVELOPMENT: IDL string2.x program ADD_PROG { version ADD_VERS { string rev(string) = 1; } = 1; } = 0x23451111;

Server /* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */ #include "string2.h" char **
University Register No:

169

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

rev_1_svc(char **argp, struct svc_req *rqstp) { static char * result; int t; int i;

char c[strlen(*argp)+1]; result = *argp; t=strlen(*argp); for(i=0;i<t;i++) { //printf("%d\n",i); c[i]=result[t-i-1]; } c[i]='\0'; strcpy(result,c); printf("%s\n",result); printf("%d\n",t); //printf("%s\n",result[1]); return &result; } Client /* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */ #include "string2.h" void add_prog_1(char *host, char **b) { CLIENT *clnt; char * *result_1; char * rev_1_arg;
University Register No:

170

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

#ifndef DEBUG clnt = clnt_create (host, ADD_PROG, ADD_VERS, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ rev_1_arg = *b; result_1 = rev_1(&rev_1_arg, clnt); if (result_1 == (char **) NULL) { clnt_perror (clnt, "call failed"); } else { printf("result = %s\n", *result_1); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ } int main (int argc, char *argv[]) { char *host; char *a; host = argv[1]; a = argv[2]; add_prog_1 (host,&a); exit (0); }

SUMMARY OF RESULTS

Client: -> ./string2_client localhost hello olleh


University Register No:

171

MITNE-107 Network Programming and Internet Lab

Department of information technology Rajagiri School of Engineering & Technology

Server: ->./string2_server olleh

CONCLUSION: Client-Server connection was established . A string entered in the client side and sends to server. Using RPC, server reverses the string, the result is returned to the client and displayed on the client side. String reversal using RPC is performed.

University Register No:

172

You might also like