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

CS9216

NETWORKING LAB(C/C++)

LIST OF EXPERIMENTS CYCLE 1 1. Socket Programming a. TCP Sockets b. UDP Sockets c. Applications using Sockets 2. Simulation of Sliding Window Protocol CYCLE-2 3. Simulation of Routing Protocols 4. Development of applications such as DNS/ HTTP/ E mail/ Multi - user Chat CYCLE-3 5. Simulation of Network Management Protocols 6. Study of Network Simulator Packages such as opnet, ns2, etc.

HARDWARE REQUIREMENTS Processor Hard disk RAM Monitor :Pentium IV :20 GB :256 MB :VGA and high resolution monitor

SOFTWARE REQUIREMENTS Operating system :LINUX Language :C/C++

Introduction to Computer Network


The network allows computers to communicate with each other and share resources and information. The Advanced Research Projects Agency (ARPA) designed "Advanced Research Projects Agency Network" (ARPANET) for the United States Department of Defense. It was the first computer network in the world in late 1960s and early 1970s.[1]

I Network classification
The following list presents categories used for classifying networks.

1.Connection method
Computer networks can also be classified according to the hardware and software technology that is used to interconnect the individual devices in the network, such as Optical fiber, Ethernet, Wireless LAN, HomePNA, Power line communication or G.hn. Ethernet uses physical wiring to connect devices. Frequently deployed devices include hubs, switches, bridges and/or routers. Wireless LAN technology is designed to connect devices without wiring. These devices use radio waves or infrared signals as a transmission medium. ITU-T G.hn technology uses existing home wiring (coaxial cable, phone lines and power lines) to create a high-speed (up to 1 Gigabit/s) local area network. Wired Technologies Twisted-Pair Wire - This is the most widely used medium for telecommunication. Twisted-pair wires are ordinary telephone wires which consist of two insulated copper wires twisted into pairs and are used for both voice and data transmission. The use of two wires twisted together helps to reduce crosstalk and electromagnetic induction. The transmission speed range from 2 million bits per second to 100 million bits per second. Coaxial Cable These cables are widely used for cable television systems, office buildings, and other worksites for local area networks. The cables consist of copper or aluminum wire wrapped with insulating layer typically of a flexible material with a high dielectric constant, all of which are surrounded by a conductive layer. The layers of insulation help minimize interference and distortion. Transmission speed range from 200 million to more than 500 million bits per second. Fiber Optics These cables consist of one or more thin filaments of glass fiber wrapped in a protective layer. It transmits light which can travel over long distance and higher bandwidths. Fiber-optic cables are not affected by electromagnetic radiation. Transmission speed could go up

to as high as trillions of bits per second. The speed of fiber optics is hundreds of times faster than coaxial cables and thousands of times faster than twisted-pair wire. Wireless Technologies Terrestrial Microwave Terrestrial microwaves use Earth-based transmitter and receiver. The equipment look similar to satellite dishes. Terrestrial microwaves use low-gigahertz range, which limits all communications to line-of-sight. Path between relay stations spaced approx. 30 miles apart. Microwave antennas are usually placed on top of buildings, towers, hills, and mountain peaks. Communications Satellites The satellites use microwave radio as their telecommunications medium which are not deflected by the Earth's atmosphere. The satellites are stationed in space, typically 22,000 miles above the equator. These Earth-orbiting systems are capable of receiving and relaying voice, data, and TV signals. Cellular and PCS Systems Use several radio communications technologies. The systems are divided to different geographic area. Each area has low-power transmitter or radio relay antenna device to relay calls from one area to the next area. Wireless LANs Wireless local area network use a high-frequency radio technology similar to digital cellular and a low-frequency radio technology. Wireless LANS use spread spectrum technology to enable communication between multiple devices in a limited area. Example of open-standard wireless radio-wave technology is IEEE 802.11b. Bluetooth A short range wireless technology. Operate at approx. 1Mbps with range from 10 to 100 meters. Bluetooth is an open wireless protocol for data exchange over short distances. The Wireless Web The wireless web refers to the use of the World Wide Web through equipments like cellular phones, pagers, PDAs, and other portable communications devices. The wireless web service offers anytime/anywhere connection.

2. Scale
Networks are often classified as Local Area Network (LAN), Wide Area Network (WAN), Metropolitan Area Network (MAN), Personal Area Network (PAN), Virtual Private Network (VPN), Campus Area Network (CAN), Storage Area Network (SAN), etc. depending on their scale, scope and purpose. Usage, trust levels and access rights often differ between these types of network - for example, LANs tend to be designed for internal use by an organization's internal systems and employees in individual physical locations (such as a building), while WANs may connect physically separate parts of an organization to each other and may include connections to third parties.

3. Functional relationship (network architecture)


Computer networks may be classified according to the functional relationships which exist among the elements of the network, e.g., Active Networking, Client-server and Peer-to-peer (workgroup) architecture.

4. Network topology
Computer networks may be classified according to the network topology upon which the network is based, such as bus network, star network, ring network, mesh network, star-bus network, tree or hierarchical topology network. Network topology signifies the way in which devices in the network see their logical relations to one another. The use of the term "logical" here is significant. That is, network topology is independent of the "physical" layout of the network. Even if networked computers are physically placed in a linear arrangement, if they are connected via a hub, the network has a Star topology, rather than a bus topology. In this regard the visual and operational characteristics of a network are distinct; the logical network topology is not necessarily the same as the physical layout. Networks may be classified based on the method of data used to convey the data, these include digital and analog networks.

II Types of networks
Below is a list of the most common types of computer networks in order of scale.

1. Personal area network


A personal area network (PAN) is a computer network used for communication among computer devices close to one person. Some examples of devices that are used in a PAN are printers, fax machines, telephones, PDAs and scanners. The reach of a PAN is typically about 20-30 feet (approximately 6-9 meters), but this is expected to increase with technology improvements.

2. Local area network


A local area network (LAN) is a computer network covering a small physical area, like a home, office, or small group of buildings, such as a school, or an airport. Current wired LANs are most likely to be based on Ethernet technology, although new standards like ITU-T G.hn also provide a way to create a wired LAN using existing home wires (coaxial cables, phone lines and power lines).

3. Campus area network


A campus area network (CAN) is a computer network made up of an interconnection of local area networks (LANs) within a limited geographical area. It can be considered one form of a metropolitan area network, specific to an academic setting.

In the case of a university campus-based campus area network, the network is likely to link a variety of campus buildings including; academic departments, the university library and student residence halls. A campus area network is larger than a local area network but smaller than a wide area network (WAN) (in some cases). The main aim of a campus area network is to facilitate students accessing internet and university resources. This is a network that connects two or more LANs but that is limited to a specific and contiguous geographical area such as a college campus, industrial complex, office building, or a military base. A CAN may be considered a type of MAN (metropolitan area network), but is generally limited to a smaller area than a typical MAN. This term is most often used to discuss the implementation of networks for a contiguous area. This should not be confused with a Controller Area Network. A LAN connects network devices over a relatively short distance. A networked office building, school, or home usually contains a single LAN, though sometimes one building will contain a few small LANs (perhaps one per room), and occasionally a LAN will span a group of nearby buildings.

4. Metropolitan area network


A metropolitan area network (MAN) is a network that connects two or more local area networks or campus area networks together but does not extend beyond the boundaries of the immediate town/city. Routers, switches and hubs are connected to create a metropolitan area network.

5. Wide area network


A wide area network (WAN) is a computer network that covers a broad area (i.e. any network whose communications links cross metropolitan, regional, or national boundaries [1]). Less formally, a WAN is a network that uses routers and public communications links Contrast with personal area networks (PANs), local area networks (LANs), campus area networks (CANs), or metropolitan area networks (MANs), which are usually limited to a room, building, campus or specific metropolitan area (e.g., a city) respectively. The largest and most well-known example of a WAN is the Internet. A WAN is a data communications network that covers a relatively broad geographic area (i.e. one city to another and one country to another country) and that often uses transmission facilities provided by common carriers, such as telephone companies. WAN technologies generally function at the lower three layers of the OSI reference model: the physical layer, the data link layer, and the network layer.

6. Global area network


A global area networks (GAN) (see also IEEE 802.20) specification is in development by several groups, and there is no common definition. In general, however, a GAN is a model for supporting mobile communications across an arbitrary number of wireless LANs, satellite coverage areas, etc. The key challenge in mobile communications is "handing off" the user communications from one local coverage area to the next. In IEEE Project 802, this involves a succession of terrestrial WIRELESS local area networks (WLAN).[4]

7. Virtual private network


A virtual private network (VPN) is a computer network in which some of the links between nodes are carried by open connections or virtual circuits in some larger network (e.g., the Internet) instead of by physical wires. The data link layer protocols of the virtual network are said to be tunneled through the larger network when this is the case. One common application is secure communications through the public Internet, but a VPN need not have explicit security features, such as authentication or content encryption. VPNs, for example, can be used to separate the traffic of different user communities over an underlying network with strong security features. A VPN may have best-effort performance, or may have a defined service level agreement (SLA) between the VPN customer and the VPN service provider. Generally, a VPN has a topology more complex than point-to-point. A VPN allows computer users to appear to be editing from an IP address location other than the one which connects the actual computer to the Internet.

8. Internetwork
An Internetwork is the connection of two or more distinct computer networks or network segments via a common routing technology. The result is called an internetwork (often shortened to internet). Two or more networks or network segments connected using devices that operate at layer 3 (the 'network' layer) of the OSI Basic Reference Model, such as a router. Any interconnection among or between public, private, commercial, industrial, or governmental networks may also be defined as an internetwork. In modern practice, interconnected networks use the Internet Protocol. There are at least three variants of internetworks, depending on who administers and who participates in them:

Intranet Extranet Internet

Intranets and extranets may or may not have connections to the Internet. If connected to the Internet, the intranet or extranet is normally protected from being accessed from the Internet without proper authorization. The Internet is not considered to be a part of the intranet or extranet, although it may serve as a portal for access to portions of an extranet. 1. Intranet An intranet is a set of networks, using the Internet Protocol and IP-based tools such as web browsers and file transfer applications, that is under the control of a single administrative entity. That administrative entity closes the intranet to all but specific, authorized users. Most commonly, an intranet is the internal network of an organization. A large intranet will typically have at least one web server to provide users with organizational information.

2. Extranet An extranet is a network or internetwork that is limited in scope to a single organization or entity but which also has limited connections to the networks of one or more other usually, but not necessarily, trusted organizations or entities (e.g., a company's customers may be given access to some part of its intranet creating in this way an extranet, while at the same time the customers may not be considered 'trusted' from a security standpoint). Technically, an extranet may also be categorized as a CAN, MAN, WAN, or other type of network, although, by definition, an extranet cannot consist of a single LAN; it must have at least one connection with an external network. 3. Internet The Internet consists of a worldwide interconnection of governmental, academic, public, and private networks based upon the networking technologies of the Internet Protocol Suite. It is the successor of the Advanced Research Projects Agency Network (ARPANET) developed by DARPA of the U.S. Department of Defense. The Internet is also the communications backbone underlying the World Wide Web (WWW). The 'Internet' is most commonly spelled with a capital 'I' as a proper noun, for historical reasons and to distinguish it from other generic internetworks. Participants in the Internet use a diverse array of methods of several hundred documented, and often standardized, protocols compatible with the Internet Protocol Suite and an addressing system (IP Addresses) administered by the Internet Assigned Numbers Authority and address registries. Service providers and large enterprises exchange information about the reachability of their address spaces through the Border Gateway Protocol (BGP), forming a redundant worldwide mesh of transmission paths.

III Basic hardware components


All networks are made up of basic hardware building blocks to interconnect network nodes, such as Network Interface Cards (NICs), Bridges, Hubs, Switches, and Routers. In addition, some method of connecting these building blocks is required, usually in the form of galvanic cable (most commonly Category 5 cable). Less common are microwave links (as in IEEE 802.12) or optical cable ("optical fiber"). An ethernet card may also be required.

1. Network interface cards


A network card, network adapter, or NIC (network interface card) is a piece of computer hardware designed to allow computers to communicate over a computer network. It provides physical access to a networking medium and often provides a low-level addressing system through the use of MAC addresses.

2. Repeaters
A repeater is an electronic device that receives a signal and retransmits it at a higher power level, or to the other side of an obstruction, so that the signal can cover longer distances without degradation. In most twisted pair Ethernet configurations, repeaters are required for cable which runs longer than 100 meters.

3. Hubs
A network hub contains multiple ports. When a packet arrives at one port, it is copied unmodified to all ports of the hub for transmission. The destination address in the frame is not changed to a broadcast address.[5]

4. Bridges
A network bridge connects multiple network segments at the data link layer (layer 2) of the OSI model. Bridges do not promiscuously copy traffic to all ports, as hubs do, but learn which MAC addresses are reachable through specific ports. Once the bridge associates a port and an address, it will send traffic for that address only to that port. Bridges do send broadcasts to all ports except the one on which the broadcast was received. Bridges learn the association of ports and addresses by examining the source address of frames that it sees on various ports. Once a frame arrives through a port, its source address is stored and the bridge assumes that MAC address is associated with that port. The first time that a previously unknown destination address is seen, the bridge will forward the frame to all ports other than the one on which the frame arrived. Bridges come in three basic types: 1. Local bridges: Directly connect local area networks (LANs) 2. Remote bridges: Can be used to create a wide area network (WAN) link between LANs. Remote bridges, where the connecting link is slower than the end networks, largely have been replaced by routers. 3. Wireless bridges: Can be used to join LANs or connect remote stations to LANs.

5. Switches
A network switch is a device that forwards and filters OSI layer 2 datagrams (chunk of data communication) between ports (connected cables) based on the MAC addresses in the packets.[6] This is distinct from a hub in that it only forwards the packets to the ports involved in the communications rather than all ports connected. Strictly speaking, a switch is not capable of routing traffic based on IP address (OSI Layer 3) which is necessary for communicating between network segments or within a large or complex LAN. Some switches are capable of routing based on IP addresses but are still called switches as a marketing term. A switch normally has numerous ports, with the intention being that most or all of the network is connected directly to the switch, or another switch that is in turn connected to a switch.[7]

Switch is a marketing term that encompasses routers and bridges, as well as devices that may distribute traffic on load or by application content (e.g., a Web URL identifier). Switches may operate at one or more OSI model layers, including physical, data link, network, or transport (i.e., end-to-end). A device that operates simultaneously at more than one of these layers is called a multilayer switch. Overemphasizing the ill-defined term "switch" often leads to confusion when first trying to understand networking. Many experienced network designers and operators recommend starting with the logic of devices dealing with only one protocol level, not all of which are covered by OSI. Multilayer device selection is an advanced topic that may lead to selecting particular implementations, but multilayer switching is simply not a real-world design concept.

6. Routers
A router is a networking device that forwards packets between networks using information in protocol headers and forwarding tables to determine the best next router for each packet. Routers work at the Network Layer of the OSI model and the Internet Layer of TCP/IP.

IV TOPOLOGIES
Network topology is the physical or logical arrangement and interconnections of the elements (links, nodes, etc.) of a computer network.[1][2] A local area network (LAN) is one example of a network that exhibits both a physical topology and a logical topology. Any given node in the LAN has one or more links to one or more other nodes in the network and the mapping of these links and nodes in a graph results in a geometrical shape that may be used to describe the physical topology of the network. Likewise, the mapping of the data flows between the nodes in the network determines the logical topology of the network. The physical and logical topologies may or may not be identical in any particular network. Any particular network topology is determined only by the graphical mapping of the configuration of physical and/or logical connections between nodes. The study of network topology uses graph theory. Distances between nodes, physical interconnections, transmission rates, and/or signal types may differ in two networks and yet their topologies may be identical.

Classification of network topologies


There are also three basic categories of network topologies:

physical topologies signal topologies logical topologies

The terms signal topology and logical topology are often used interchangeably, though there is a subtle difference between the two.

1. Physical topologies The mapping of the nodes of a network and the physical connections between them i.e., the layout of wiring, cables, the locations of nodes, and the interconnections between the nodes and the cabling or wiring system[1]. Classification of physical topologies

Point-to-point
The simplest topology is a permanent link between two endpoints (the line in the illustration above). Switched point-to-point topologies are the basic model of conventional telephony. The value of a permanent point-to-point network is the value of guaranteed, or nearly so, communications between the two endpoints. The value of an on-demand point-to-point connection is proportional to the number of potential pairs of subscribers, and has been expressed as Metcalfe's Law. Permanent (dedicated) Easiest to understand, of the variations of point-to-point topology, is a point-to-point communications channel that appears, to the user, to be permanently associated with the two endpoints. Children's "tin-can telephone" is one example, with a microphone to a single public address speaker is another. These are examples of physical dedicated channels. Within many switched telecommunications systems, it is possible to establish a permanent circuit. One example might be a telephone in the lobby of a public building, which is programmed to ring only the number of a telephone dispatcher. "Nailing down" a switched connection saves the cost of running a physical circuit between the two points. The resources in such a connection can be released when no longer needed, for example, a television circuit from a parade route back to the studio. Switched: Using circuit-switching or packet-switching technologies, a point-to-point circuit can be set up dynamically, and dropped when no longer needed. This is the basic mode of conventional telephony.

Bus
Bus network topology In local area networks where bus technology is used, each machine is connected to a single cable. Each computer or server is connected to the single bus cable through some kind of connector. A terminator is required at each end of the bus cable to prevent the signal from bouncing back and forth on the bus cable. A signal from the source travels in both directions to all machines connected on the bus cable until it finds the MAC address or IP address on the network that is the intended recipient. If the machine address does not match the intended address for the data, the machine ignores the data. Alternatively, if the data does match the machine address, the data is accepted. Since the bus topology consists of only one wire, it is rather inexpensive to implement when compared to other

topologies. However, the low cost of implementing the technology is offset by the high cost of managing the network. Additionally, since only one cable is utilized, it can be the single point of failure. If the network cable breaks, the entire network will be down, since there is only one cable. Since there is one cable, the transfer speeds between the computers on the network is faster. Linear bus The type of network topology in which all of the nodes of the network are connected to a common transmission medium which has exactly two endpoints (this is the 'bus', which is also commonly referred to as the backbone, or trunk) all data that is transmitted between nodes in the network is transmitted over this common transmission medium and is able to be received by all nodes in the network virtually simultaneously (disregarding propagation delays). Note: The two endpoints of the common transmission medium are normally terminated with a device called a terminator that exhibits the characteristic impedance of the transmission medium and which dissipates or absorbs the energy that remains in the signal to prevent the signal from being reflected or propagated back onto the transmission medium in the opposite direction, which would cause interference with and degradation of the signals on the transmission medium (See Electrical termination). Distributed bus The type of network topology in which all of the nodes of the network are connected to a common transmission medium which has more than two endpoints that are created by adding branches to the main section of the transmission medium the physical distributed bus topology functions in exactly the same fashion as the physical linear bus topology (i.e., all nodes share a common transmission medium). Notes: 1.) All of the endpoints of the common transmission medium are normally terminated with a device called a 'terminator'. 2.) The physical linear bus topology is sometimes considered to be a special case of the physical distributed bus topology i.e., a distributed bus with no branching segments. 3.) The physical distributed bus topology is sometimes incorrectly referred to as a physical tree topology however, although the physical distributed bus topology resembles the physical tree topology, it differs from the physical tree topology in that there is no central node to which any other nodes are connected, since this hierarchical functionality is replaced by the common bus.

Star
Star network topology In local area networks where the star topology is used, each machine is connected to a central hub. In contrast to the bus topology, the star topology allows each machine on the network to have a point to point connection to the central hub. All of the traffic which transverses the network passes through the central hub. The hub acts as a signal booster or repeater which in turn allows the signal to travel greater distances. As a result of each machine connecting directly to the hub, the star topology is considered the easiest topology to design and implement. An

advantage of the star topology is the simplicity of adding other machines. The primary disadvantage of the star topology is the hub is a single point of failure. If the hub were to fail the entire network would fail as a result of the hub being connected to every machine on the network. Notes: 1.) A point-to-point link (described above) is sometimes categorized as a special instance of the physical star topology therefore, the simplest type of network that is based upon the physical star topology would consist of one node with a single point-to-point link to a second node, the choice of which node is the 'hub' and which node is the 'spoke' being arbitrary[1]. 2.) After the special case of the point-to-point link, as in note 1.) above, the next simplest type of network that is based upon the physical star topology would consist of one central node the 'hub' with two separate point-to-point links to two peripheral nodes the 'spokes'. 3.) Although most networks that are based upon the physical star topology are commonly implemented using a special device such as a hub or switch as the central node (i.e., the 'hub' of the star), it is also possible to implement a network that is based upon the physical star topology using a computer or even a simple common connection point as the 'hub' or central node however, since many illustrations of the physical star network topology depict the central node as one of these special devices, some confusion is possible, since this practice may lead to the misconception that a physical star network requires the central node to be one of these special devices, which is not true because a simple network consisting of three computers connected as in note 2.) above also has the topology of the physical star. 4.) Star networks may also be described as either broadcast multi-access or nonbroadcast multi-access (NBMA), depending on whether the technology of the network either automatically propagates a signal at the hub to all spokes, or only addresses individual spokes with each communication. Extended star A type of network topology in which a network that is based upon the physical star topology has one or more repeaters between the central node (the 'hub' of the star) and the peripheral or 'spoke' nodes, the repeaters being used to extend the maximum transmission distance of the point-to-point links between the central node and the peripheral nodes beyond that which is supported by the transmitter power of the central node or beyond that which is supported by the standard upon which the physical layer of the physical star network is based. Note: If the repeaters in a network that is based upon the physical extended star topology are replaced with hubs or switches, then a hybrid network topology is created that is referred to as a physical hierarchical star topology, although some texts make no distinction between the two topologies. Distributed Star A type of network topology that is composed of individual networks that are based upon the physical star topology connected together in a linear fashion i.e., 'daisy-chained' with no central or top level connection point (e.g., two or more 'stacked' hubs, along with their associated star connected nodes or 'spokes').

Ring
Ring network topology In local area networks where the ring topology is used, each computer is connected to the network in a closed loop or ring. Each machine or computer has a unique address that is used for identification purposes. The signal passes through each machine or computer connected to the ring in one direction. Ring topologies typically utilize a token passing scheme, used to control access to the network. By utilizing this scheme, only one machine can transmit on the network at a time. The machines or computers connected to the ring act as signal boosters or repeaters which strengthen the signals that transverse the network. The primary disadvantage of ring topology is the failure of one machine will cause the entire network to fail.

Mesh
The value of fully meshed networks is proportional to the exponent of the number of subscribers, assuming that communicating groups of any two endpoints, up to and including all the endpoints, is approximated by Reed's Law.

Fully connected mesh topology Fully connected The type of network topology in which each of the nodes of the network is connected to each of the other nodes in the network with a point-to-point link this makes it possible for data to be simultaneously transmitted from any single node to all of the other nodes. Note: The physical fully connected mesh topology is generally too costly and complex for practical networks, although the topology is used when there are only a small number of nodes to be interconnected. Partially connected mesh topology Partially connected The type of network topology in which some of the nodes of the network are connected to more than one other node in the network with a point-to-point link this makes it possible to take advantage of some of the redundancy that is provided by a physical fully connected mesh topology without the expense and complexity required for a connection between every node in the network. Note: In most practical networks that are based upon the physical partially connected mesh topology, all of the data that is transmitted between nodes in the network takes the shortest path (or an approximation of the shortest path) between nodes, except in the case of a failure or break in one of the links, in which case the data takes an alternate path to the destination. This requires that the nodes of the network possess some type of logical 'routing' algorithm to determine the correct path to use at any particular time.

Tree
Tree network topology Also known as a hierarchical network. The type of network topology in which a central 'root' node (the top level of the hierarchy) is connected to one or more other nodes that are one level lower in the hierarchy (i.e., the second level) with a point-to-point link between each of the second level nodes and the top level central 'root' node, while each of the second level nodes that are connected to the top level central 'root' node will also have one or more other nodes that are one level lower in the hierarchy (i.e., the third level) connected to it, also with a point-to-point link, the top level central 'root' node being the only node that has no other node above it in the hierarchy (The hierarchy of the tree is symmetrical.) Each node in the network having a specific fixed number, of nodes connected to it at the next lower level in the hierarchy, the number, being referred to as the 'branching factor' of the hierarchical tree. 1.) A network that is based upon the physical hierarchical topology must have at least three levels in the hierarchy of the tree, since a network with a central 'root' node and only one hierarchical level below it would exhibit the physical topology of a star. 2.) A network that is based upon the physical hierarchical topology and with a branching factor of 1 would be classified as a physical linear topology. 3.) The branching factor, f, is independent of the total number of nodes in the network and, therefore, if the nodes in the network require ports for connection to other nodes the total number of ports per node may be kept low even though the total number of nodes is large this makes the effect of the cost of adding ports to each node totally dependent upon the branching factor and may therefore be kept as low as required without any effect upon the total number of nodes that are possible. 4.) The total number of point-to-point links in a network that is based upon the physical hierarchical topology will be one less than the total number of nodes in the network. 5.) If the nodes in a network that is based upon the physical hierarchical topology are required to perform any processing upon the data that is transmitted between nodes in the network, the nodes that are at higher levels in the hierarchy will be required to perform more processing operations on behalf of other nodes than the nodes that are lower in the hierarchy. Such a type of network topology is very useful and highly recommended.

2. Signal topology
The mapping of the actual connections between the nodes of a network, as evidenced by the path that the signals take when propagating between the nodes. Note: The term 'signal topology' is often used synonymously with the term 'logical topology', however, some confusion may result from this practice in certain situations since, by definition, the term 'logical topology' refers to the apparent path that the data takes between nodes in a network while the term 'signal topology' generally refers to the actual path that the signals (e.g., optical, electrical, electromagnetic, etc.) take when propagating between nodes.

Example

3. Logical topology
The logical topology, in contrast to the "physical", is the way that the signals act on the network media, or the way that the data passes through the network from one device to the next without regard to the physical interconnection of the devices. A network's logical topology is not necessarily the same as its physical topology. For example, twisted pair Ethernet is a logical bus topology in a physical star topology layout. While IBM's Token Ring is a logical ring topology, it is physically set up in a star topology. Classification of logical topologies The logical classification of network topologies generally follows the same classifications as those in the physical classifications of network topologies, the path that the data takes between nodes being used to determine the topology as opposed to the actual physical connections being used to determine the topology. Notes: 1.) Logical topologies are often closely associated with media access control (MAC) methods and protocols. 2.) The logical topologies are generally determined by network protocols as opposed to being determined by the physical layout of cables, wires, and network devices or by the flow of the electrical signals, although in many cases the paths that the electrical signals take between nodes may closely match the logical flow of data, hence the convention of using the terms 'logical topology' and 'signal topology' interchangeably. 3.) Logical topologies are able to be dynamically reconfigured by special types of equipment such as routers and switches.

ADVANATAGES
1. 2. 3. 4. 5. Security/Encapsulation Security through redundancy Faster Problem Solving Collaborative Processing Distributed Databases

APPLICATIONS
1. 2. 3. 4. 5. 6. 7. Maketing and Sales Financial Services Manufacturing Electronic Data Interchange Electronic Messaging Information Services Directory Services

8. Cellular Telephony 9. Cable Television 10. Video Conferencing RELATED TEXT BOOKS 1. Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004. 2. James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3. Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4. Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5. William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000.

RELATED WEB LINKS


1. www.wikipedia.com 2. www.google.com 3. www.altavista.com

Ex. No. 0

Study of Socket Programming

Client Server Architecture


In the client server architecture, a machine(refered as client) makes a request to connect to another machine (called as server) for providing some service. The services running on the server run on known ports(application identifiers) and the client needs to know the address of the server machine and this port in order to connect to the server. On the other hand, the server does not need to know about the address or the port of the client at the time of connection initiation. The first packet which the client sends as a request to the server contains these informations about the client which are further used by the server to send any information. Client acts as the active device which makes the first move to establish the connection whereas the server passively waits for such requests from some client.

Illustration of Client Server Model

What is a Socket ?
In unix, whenever there is a need for inter process communication within the same machine, we use mechanism like signals or pipes(named or unnamed). Similarly, when we desire a communication between two applications possibly running on different machines, we need sockets. Sockets are treated as another entry in the unix open file table. So all the system calls which can be used for any IO in unix can be used on socket. The server and client applications use various system calls to conenct which use the basic construct called socket. A socket is one end of the communication channel between two applications running on different machines. Steps followed by client to establish the connection: 1. 2. 3. 4. Create a socket Connect the socket to the address of the server Send/Receive data Close the socket

Steps followed by server to establish the connection:

1. 2. 3. 4. 5.

Create a socket Bind the socket to the port number known to all clients Listen for the connection request Accept connection request Send/Receive data

Basic data structures used in Socket programming


Socket Descriptor: A simple file descriptor in Unix. int Socket Address: This construct holds the information for socket address
struct sockaddrs { unsigned short char }; sa_family; sa_data[14]; // address family, AF_xxx or PF_xxx // 14 bytes of protocol address

AF stands for Address Family and PF stands for Protocol Family. In most modern implementations only the AF is being used. The various kinds of AF are as follows:
Name AF_UNIX, AF_LOCAL AF_INET AF_INET6 AF_IPX AF_NETLINK AF_X25 AF_AX25 AF_ATMPVC AF_APPLETALK AF_PACKET Purpose Local communication IPv4 Internet protocols IPv6 Internet protocols IPX - Novell protocols Kernel user interface device ITU-T X.25 / ISO-8208 protocol Amateur radio AX.25 protocol Access to raw ATM PVCs Appletalk Low level packet interface

In all the sample programs given below, we will be using AF_INET. struct sockaddr_in: This construct holds the information about the address family, port number, Internet address,and the size of the struct sockaddr.
struct sockaddr_in { short int unsigned short int struct in_addr unsigned char }; sin_family; sin_port; sin_addr; sin_zero[8]; // // // // Address family Port number Internet address Same size as struct sockaddr

Some systems (like x8086) are Little Endian i-e. least signficant byte is stored in the higher address, whereas in Big endian systems most significant byte is stored in the higher address. Consider a situation where a Little Endian system wants to communicate with a Big Endian one, if there is no standard for data representation then the data sent by one machine is misinterpreted by the other. So standard has been defined for the data representation in the network (called Network Byte Order) which is the Big Endian. The system calls that help us to convert a short/long from Host Byte order to Network Byte Order and viceversa are

htons() -- "Host to Network Short" htonl() -- "Host to Network Long"

ntohs() -- "Network to Host Short" ntohl() -- "Network to Host Long"

IP addresses
Assuming that we are dealing with IPv4 addresses, the address is a 32bit integer. Remembering a 32 bit number is not convenient for humans. So, the address is written as a set of four integers seperated by dots, where each integer is a representation of 8 bits. The representation is like a.b.c.d, where a is the representation of the most significant byte. The system call which converts this representation into Network Byte Order is:
int inet_aton(const char *cp, struct in_addr *inp);

inet_aton() converts the Internet host address cp from the standard numbers-and-dots notation into binary data and stores it in the structure that inp points to. inet_aton returns nonzero if the address is valid, zero if not. For example, if we want to initialize the sockaddr_in construct by the IP address and desired port number, it is done as follows:
struct sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons(21); inet_aton("172.26.117.168", &(sockaddr.sin_addr)); memset(&(sockaddr.sin_zero), '\0', 8);

Socket System Call


A socket is created using the system call:
int socket( domain , type , protocol);

This system call returns a Socket Descriptor (like file descriptor) which is an integer value. Details about the Arguments: 1. Domain: It specifies the communication domain. It takes one of the predefined values described under the protocol family and address family above. 2. Type: It specifies the semantics of communication , or the type of service that is desired . It takes the following values: o SOCK_STREAM : Stream Socket o SOCK_DGRAM : Datagram Socket o SOCK_RAW : Raw Socket o SOCK_SEQPACKET : Sequenced Packet Socket o SOCK_RDM : Reliably Delivered Message Packet 3. Protocol: This parameter identifies the protocol the socket is supposed to use . Some values are as follows: o IPPROTO_TCP : For TCP (SOCK_STREAM) o IPPROTO_UDP : For UDP (SOCK_DRAM)

Since we have only one protocol for each kind of socket, it does not matter if we do not define any protocol at all. So for simplicity, we can put "0" (zero) in the protocol field.

Bind System Call


The system call bind associates an address to a socket descriptor created by socket.
int bind ( int sockfd , struct sockaddr *myaddr , int addrlen );

The second parameter myaddr specifies a pointer to a predefined address of the socket.Its structure is a general address structure so that the bind system call can be used by both Unix domain and Internet domain sockets.

Other System Calls and their Functions


LISTEN : Annoumce willingness to accept connections ; give queue size. ACCEPT : Block the caller until a commwction attempt arrives. CONNECT : Actively attempt to establish a connection. SEND : Send some data over the connection. RECIEVE : Recieve sme data from the connection. CLOSE : Release the connection.

Client-Server Communication Overview


The analogy given below is often very useful in understanding many such networking concepts. The analogy is of a number of people in a room communicating with each other by way of talking. In a typical scenario, if A has to talk to B, then he would call out the name of B and only if B was listening would he respond. In case B responds, then one can say that a connection has been established. Henceforth until both of them desire to communicate, they can carry out their conversation. A Client-Server architecture generally employed in networks is also very similar in concept. Each machine can act as a client or a server. Server: It is normally defined which provides some sevices to the client programs. However, we will have a deeper look at the concept of a "service" in this respect later. The most important feature of a server is that it is a passive entiry, one that listens for request from the clients. Client: It is the active entity of the architecture, one that generated this request to connect to a particular port number on a particular server Communication takes the form of the client process sending a message over the network to the server process. The client process then waits for a reply message. When the server process gets the request, it performs the requested work and sends back a reply.The server that the client will try to connect to should be up and running before the client can be executed. In most of the cases, the servers runs continuously as a daemon.

There is a general misconception that servers necessarily provide some service and is therefore called a server. For example an e-mail client provides as much service as an mail server does. Actually the term service is not very well defined. So it would be better not to refer to the term at all. In fact servers can be programmed to do practically anything that a normal application can do. In brief, a server is just an entity that listens/waits for requests. To send a request, the client needs to know the address of the server as well as the port number which has to be supplied to establish a connection. One option is to make the server choose a random number as a port number, which will be somehow conveyed to the client. Subsequently the client will use this port number to send requests. This method has severe limitations as such information has to be communicated offline, the network connection not yet being established. A better option would be to ensure that the server runs on the same port number always and the client already has knowledge as to which port provides which service. Such a standardization already exists. The port numbers 0-1023 are reserved for the use of the superuser only. The list of the services and the ports can be found in the file /etc/services.

Connection Oriented vs Connectionless Communication


Connection Oriented Communication Analogous to the telephone network.The sender requests for a communication (dial the number), the receiver gets an indication (the phone ring) the receiver accepts the connection (picks up the phone) and the sender receives the acknowledgment (the ring stops). The connection is established through a dedicated link provided for the communication. This type of communication is characterized by a high level of reliability in terms of the number and the sequence of bytes. Connectionless Communication Analogous to the postal service. Packets(letters) are sent at a time to a particular destination. For greater reliability, the receiver may send an acknowledgement (a receipt for the registered letters). Based on this two types of communication, two kinds of sockets are used:

stream sockets: used for connection-oriented communication, when reliability in connection is desired. datagram sockets: used for connectionless communication, when reliability is not as much as an issue compared to the cost of providing that reliability. For eg. streaming audio/video is always send over such sockets so as to diminish network traffic.

Sequence of System Calls for Connection Oriented communication The typical set of system calls on both the machines in a connection-oriented setup is shown in Figure below.

The sequence of system calls that have to be made in order to setup a connection is given below. 1. The socket system call is used to obtain a socket descriptor on both the client and the server. Both these calls need not be synchronous or related in the time at which they are called.The synopsis is given below: #include<sys/types.h> #include<sys/socket.h> int socket(int domain, int type, int protocol); 2. Both the client and the server 'bind' to a particular port on their machines using the bind system call. This function has to be called only after a socket has been created and has to be passed the socket descriptor returned by the socket call. Again this binding on both the machines need not be in any particular order. Moreover the binding procedure on the client is entirely optional. The bind system call requires the address family, the port number and the IP address. The address family is known to be AF_INET, the IP address of the client is already known to the operating system. All that remains is the port number. Of course the programmer can specify which port to bind to, but this is not necessary. The binding can be done on a random port as well and still everything would work fine. The way to make this happen is not to call bind at all. Alternatively bind can be called with the port number set to 0. This tells the operating system to assign a random port number to this socket. This way whenever the program tries to connect to a remote machine through this socket, the operating system binds this socket to a random local

port. This procedure as mentioned above is not applicable to a server, which has to listen at a standard predetermined port. 3. The next call has to be listen to be made on the server. The synopsis of the listen call is given below. #include<sys/socket.h> int listen(int skfd, int backlog); 4. skfd is the socket descriptor of the socket on which the machine should start listening. backlog is the maximum length of the queue for accepting requests. 5. The connect system call signifies that the server is willing to accept connections and thereby start communicating. 6. Actually what happens is that in the TCP suite, there are certain messages that are sent to and fro and certain initializations have to be performed. Some finite amount of time is required to setup the resources and allocate memory for whatever data structures that will be needed. In this time if another request arrives at the same port, it has to wait in a queue. Now this queue cannot be arbitrarily large. After the queue reaches a particular size limit no more requests are accepted by the operating system. This size limit is precisely the backlog argument in the listen call and is something that the programmer can set. Today's processors are pretty speedy in their computations and memory allocations. So under normal circumstances the length of the queue never exceeds 2 or 3. Thus a backlog value of 2-3 would be fine, though the value typically used is around 5.Note that this call is different from the concept of "parallel" connections.The established connections are not counted in n. So, we may have 100 parallel connection running at a time when n=5.

7. The connect function is then called on the client with three arguments, namely the socket descriptor, the remote server address and the length of the address data structure. The synopsis of the function is as follows:

#include<sys/socket.h> #include<netinet/in.h> /* only for AF_INET , or the INET Domain */ int connect(int skfd, struct sockaddr* addr, int addrlen); This function initiates a connection on a socket. skfd is the same old socket descriptor. addr is again the same kind of structure as used in the bind system call. More often than not, we will be creating a structure of the type sockaddr_in instead of sockaddr and filling it with appropriate data. Just while sending the pointer to that structure to the connect or even the bind system call, we cast it into a pointer to a sockaddr structure. The reason for doing all this is that the sockaddr_in is more convenient to use in case of INET

domain applications. addr basically contains the port number and IP address of the server which the local machine wants to connect to. This call normally blocks until either the connection is established or is rejected. addrlen is the length of the socket address structure, the pointer to which is the second argument. 8. The request generated by this connect call is processed by the remote server and is placed in an operating system buffer, waiting to be handed over to the application which will be calling the accept function. The accept call is the mechanism by which the networking program on the server receives that requests that have been accepted by the operating system. This synopsis of the accept system call is given below. #include<sys/socket.h> int accept(int skfd, struct sockaddr* addr, int addrlen); skfd is the socket descriptor of the socket on which the machine had performed a listen call and now desires to accept a request on that socket. addr is the address structure that will be filled in by the operating system by the port number and IP address of the client which has made this request. This sockaddr pointer can be type-casted to a sockaddr_in pointer for subsequent operations on it. addrlen is again the length of the socket address structure, the pointer to which is the second argument.

This function accept extracts aconnection on the buffer of pending connections in the system, creates a new socket with the same properties as skfd, and returns a new file descriptor for the socket. In fact, such an architecture has been criticized to the extent that the applications do not have a say on what connections the operating system should accept. The system accepts all requests irrespective of which IP, port number they are coming from and which application they are for. All such packets are processed and sent to the respective applications, and it is then that the application can decide what to do with that request. The accept call is a blocking system call. In case there are requests present in the system buffer, they will be returned and in case there aren't any, the call simply blocks until one arrives. This new socket is made on the same port that is listening to new connections. It might sound a bit weird, but it is perfectly valid and the new connection made is indeed a unique connection. Formally the definition of a connection is connection: defined as a 4-tuple : (Local IP, Local port, Foreign IP, Foreign port)

For each connection at least one of these has to be unique. Therefore multiple connections on one port of the server, actually are different. 9. Finally when both connect and accept return the connection has been established. 10. The socket descriptors that are with the server and the client can now be used identically as a normal I/O descriptor. Both the read and the write calls can be performed on this socket descriptor. The close call can be performed on this descriptor to close the connection. Man pages on any UNIX type system will furnish further details about these generic I/O calls. 11. Variants of read and write also exist, which were specifically designed for networking applications. These are recv and send. #include<sys/socket.h> int recv(int skfd, void *buf, int buflen, int flags); int send(int skfd, void *buf, int buflen, int flags); Except for the flags argument the rest is identical to the arguments of the read and write calls. Possible values for the flags are:

used for recv send recv send &

macro for the flag MSG_PEEK MSG_DONT_ROUTE MSG_OOB

comment look at the message in the buffer but do not consider it read send message only if the destination is on the same network, i.e. directly connected to the local machine. used for transferring data out of sequence, when some bytes in a stream might be more important than others.

12. To close a particular connection the shutdown call can also be used to achieve greater flexibility.

#include<sys/socket.h> int shutdown(int skfd, int how);

skfd is how

the

socket can

descriptor be

of

the one

socket which of

needs the

to

be closed. following:

o 0stop all read operations on this socket, but continue writing r o SHUT_WR 1stop all write operations on this socket, but keep receiving data r o SHUT_RDWR 2same as close r SHUT_RD A port can be reused only if it has been closed completely.

Sequence of System Calls for Connectionless Communication The typical set of system calls on both the machines in a connectionless setup is shown in Figure below.

The socket and bind system calls are called in the same way as in the connectionoriented case. Again the bind call is optional at the client side.

The connect function is not called in a connectionless communication with the sane intention as above. Instead, if we call a connect() in this case, then we are simply specifying a particular server address to which we have to send, and from which we have to receive the Datagrams Every time a packet has to be sent over a socket, the remote address has to be mentioned. This is because there is no concept of a connection that can remember which remote machine to send that packet to. The calls sendto and recvfrom are used to send datagram packets. The synopses of both are given below. int sendto(int skfd, void *buf, int buflen, int flags, struct sockaddr* to, int tolen); int recvfrom(int skfd, void *buf, int buflen, int flags, struct sockaddr* from, int fromlen); sendto sends a datagram packet containing the data present in buf addressed to the address present in the sockaddr structure, to. recvfrom fills in the buf structure with the data received from a datagram packet and the sockaddr structure, from with the address of the client from which the packet was received. Both these calls block until a packet is sent in case of sendto and a packet is received in case of recvfrom. In the strict sense though sendto is not blocking as the packet is sent out in most cases and sendto returns immediately.

Suppose if the program desires to communicate only to one particular machine and make the operating system discard packets from all other machines, it can use the connect call to specify the address of the machine with which it will exclusively communicate. All subsequent calls do not require the address field to be given. It will be understood that the remote address is the one specified in connect called earlier.

Reserved Ports
Port numbers from 1-1023 are reserved for the superuser and the rest of the ports starting from 1024 are for other users. But we have a finer division also which is as follows :

1 to 511 - these are assigned to the processes run by the superuser 512 to 1023 - they are used when we want to assign ports to some important user or process but want to show that this is a reserved superuser port 1024 to 5000 - they are system assigned random ports 5000 to FFFF - they are used to assign a port to user processes or sockets used by users

RELATED TEXT BOOKS

1.Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004. 2.James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3.Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4.Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5.William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000.

RELATED WEB LINKS


1. www.wikipedia.com 2. www.google.com 3.www.altavista.com

Ex. No. 1

Transmission Control Protocol

Function
TCP provides a communication service at an intermediate level between an application program and the Internet Protocol (IP). That is, when an application program desires to send a large chunk of data across the Internet using IP, instead of breaking the data into IP-sized pieces and issuing a series of IP requests, the software can issue a single request to TCP and let TCP handle the IP details. IP works by exchanging pieces of information called packets. A packet is a sequence of bytes and consists of a header followed by a body. The header describes the packet's destination and, optionally, the routers to use for forwarding until it arrives at its final destination. The body contains the data which IP is transmitting. Due to network congestion, traffic load balancing, or other unpredictable network behavior, IP packets can be lost or delivered out of order. TCP detects these problems, requests retransmission of lost packets, rearranges out-of-order packets, and even helps minimize network congestion to reduce the occurrence of the other problems. Once the TCP receiver has finally reassembled a perfect copy of the data originally transmitted, it passes that datagram to the application program. Thus, TCP abstracts the application's communication from the underlying networking details. TCP is used extensively by many of the Internet's most popular applications, including the World Wide Web, E-mail, File Transfer Protocol, Secure Shell, and some streaming media applications. TCP is optimized for accurate delivery rather than timely delivery, and therefore, TCP sometimes incurs relatively long delays (in the order of seconds) while waiting for out-of-order messages or retransmissions of lost messages. It is not particularly suitable for real-time applications such as Voice over IP. For such applications, protocols like the Real-time Transport Protocol (RTP) running over the User Datagram Protocol (UDP) are usually recommended instead. TCP is a reliable stream delivery service that guarantees delivery of a data stream sent from one host to another without duplication or losing data. Since packet transfer is not reliable, a technique known as positive acknowledgment with retransmission is used to guarantee reliability of packet transfers. This fundamental technique requires the receiver to respond with an acknowledgment message as it receives the data. The sender keeps a record of each packet it sends, and waits for acknowledgment before sending the next packet. The sender also keeps a timer from when the packet was sent, and retransmits a packet if the timer expires. The timer is needed in case a packet gets lost or corrupted.[2] TCP consists of a set of rules: for the protocol, that are used with the Internet Protocol, and for the IP, to send data "in a form of message units" between computers over the Internet. At the same time that IP takes care of handling the actual delivery of the data, TCP takes care of keeping track of the individual units of data transmission, called segments, that a message is divided into for efficient routing through the network. For example, when an HTML file is sent from a Web server, the TCP software layer of that server divides the sequence of bytes of the file

into segments and forwards them individually to the IP software layer (Internet Layer). The Internet Layer encapsulates each TCP segment into an IP packet by adding a header which includes (among other data) the destination IP address. Even though every packet has the same destination address, they can be routed on different paths through the network. When the client program on the destination computer receives them, the TCP layer (Transport Layer) reassembles the individual segments and ensures they are correctly ordered and errorfree as it streams them to an application.

TCP segment structure


A TCP segment consists of two sections:

header data

The TCP header consists of 11 fields, of which only 10 are required. The eleventh field is optional (pink background in table) and is aptly named "options". TCP Header Bit offset 0 32 64

03

47

815

1631

Source port Sequence number Acknowledgment number Data Reserved CWR ECE URG ACK PSH RST SYN FIN offset Checksum Options (optional)

Destination port

96

Window Size

128 160

Urgent pointer

160/192+

Data

Source port (16 bits) identifies the sending port Destination port (16 bits) identifies the receiving port Sequence number (32 bits) has a dual role If the SYN flag is set, then this is the initial sequence number. The sequence number of the actual first data byte will then be this sequence number plus 1. If the SYN flag is not set, then this is the sequence number of the first data byte

Acknowledgement number (32 bits) if the ACK flag is set then the value of this field is the next expected sequence number that the receiver is expecting. Data offset (4 bits) specifies the size of the TCP header in 32-bit words. The minimum size header is 5 words and the maximum is 15 words thus giving the minimum size of 20 bytes and maximum of 60 bytes. This field gets its name from the fact that it is also the offset from the start of the TCP segment to the actual data. Reserved (4 bits) for future use and should be set to zero Flags (8 bits) (aka Control bits) contains 8 1-bit flags CWR (1 bit) Congestion Window Reduced (CWR) flag is set by the sending host to indicate that it received a TCP segment with the ECE flag set and had responded in congestion control mechansim (added to header by RFC 3168). ECE (ECN-Echo) (1 bit) indicates (1) that the TCP peer is ECN capable during 3-way handshake, and (2) that a packet with Congestion Experienced flag in IP header set is received during normal transmission(added to header by RFC 3168). URG (1 bit) indicates that the URGent pointer field is significant ACK (1 bit) indicates that the ACKnowledgment field is significant PSH (1 bit) Push function RST (1 bit) Reset the connection SYN (1 bit) Synchronize sequence numbers FIN (1 bit) No more data from sender

Window (16 bits) the size of the receive window, which specifies the number of bytes (beyond the sequence number in the acknowledgment field) that the receiver is currently willing to receive (see Flow control) Checksum (16 bits) The 16-bit checksum field is used for error-checking of the header and data Urgent pointer (16 bits) if the URG flag is set, then this 16-bit field is an offset from the sequence number indicating the last urgent data byte

Options (Variable bits) the total length of the option field must be a multiple of a 32-bit word and the data offset field adjusted appropriately

The last field is not a part of the header. The contents of this field are whatever the upper layer protocol wants but this protocol is not set in the header and is presumed based on the port selection.

Data (Variable bits): As you might expect, this is the payload, or data portion of a TCP packet. The payload may be any number of application layer protocols. The most common are HTTP, Telnet, SSH, FTP, but other popular protocols also use TCP.

ADVANTAGES
1. Reliable 2. Connection Oriented 3. Suitable for bulk data transfer

DISADVANTAGES
1. More overhead in connection establishment

APPLICATIONS
1. Supports Applications like email, DNS. 2. Used in Congestion control 3. TCP/IP data can be sent across a LAN, or it can be carried within an internal corporate SNA network, or it can piggyback on the cable TV service.

Ex.no:1 Date:
AIM

CLIENT-SERVER CHAT PROGRAM USING TCP

To write a C program for implementing Client-Server Chat using TCP.

ALGORITHM SERVER
Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as type. Step 3: Name the socket using bind( ) system call with the parameters server_sockfd and the server address(sin_addr and sin_sport). Step 4: Create a connection queue and wait for clients using the listen( ) system call with the number of clients request as parameters. Step 5: Accept the connection using accept( ) system call when client requests for connection. Step 6: Get the message which has to be sent to the client and check that it is not equal to Bye. Step 7: If the message is not equal to Bye then write the message to the client and Goto step 6. Step 8: If the message is Bye then terminate the Process. Step 9: Stop the program execution.

CLIENT
Step 1: Start the program. Step 2: Create an unnamed socket for client using socket( ) system. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type. Step 4: Name the socket using bind( ) system call. Step 5: Now connect the socket to server using connect( ) system call. Step 6: Read the message from the server socket and compare it with Bye. Step 7: If the message is not equal to Bye then print the message to the server output device and repeat the steps 6 & 7. Step 8: Get the message from the client side. Step 9: Write the message to server sockfd and goto step 4. Step 10:If the message is equal to Byethen print good bye message and terminate the process. Step 11:Stop the process.

CLIENT SERVER CHAT USING TCP SERVER


#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int sd,sd2,nsd,clilen,sport,len; char sendmsg[20],rcvmsg[20]; struct sockaddr_in servaddr,cliaddr; printf("Enter the Server port"); printf("\n_____________________\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf(" Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); printf("\nReceived Messages\n"); do { recv(nsd,rcvmsg,20,0); printf("%s",rcvmsg); fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0';

send(nsd,sendmsg,20,0); wait(20); } while(strcmp(sendmsg,"bye")!=0); }

CLIENT
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],revmsg[20]; struct sockaddr_in servaddr; printf("Enter the port\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Scocket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); do { fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(csd,sendmsg,20,0); wait(20); recv(csd,revmsg,20,0); printf("%s",revmsg); } while(strcmp(revmsg,"bye")!=0); }

OUTPUT:
Client Side [1me16@localhost ~]$ cc tcpclient.c [1me16@localhost ~]$. /a.out Enter the port 6523 Socket is Created Connected Hello Server Side [1me16@localhost ~]$ cc tcpserver.c.c [1me16@localhost ~]$. /a.out Enter the server port 6543 Socket is Created Binded Accepted Received Messages. Hello

RESULT
Thus the C program for chat using TCP is executed and the output is verified successfully

Ex. No. 2

User Datagram Protocol

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 requiring prior communications to set up special transmission channels or data paths. UDP is sometimes called the Universal Datagram Protocol. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768.[1] UDP uses a simple transmission model without implicit hand-shaking dialogues for guaranteeing reliability, ordering, or data integrity. Thus, UDP provides an unreliable service and datagrams may arrive out of order, appear duplicated, or go missing without notice. UDP assumes that 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 using delayed packets. 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. UDP's stateless nature is also useful for servers that answer small queries from huge numbers of clients. Unlike TCP, UDP is compatible with packet broadcast (sending to all on local network) and multicasting (send to all subscribers).

Ports
UDP applications use datagram sockets to establish host-to-host communications. Sockets bind the application to service ports, that function as the endpoints of data transmission. A port is a software structure that is identified by the port number, a 16 bit integer value, allowing for port numbers between 0 and 65,535. Port 0 is reserved, but is a permissible source port value if the sending process does not expect messages in response. Ports 1 through 1023 (hexadecimal 0x3FF) are named "well-known" ports and on Unix-like operating systems, binding to one of these ports requires superuser (root) access. Ports 1024 through 49,151 (0xBFFF) are the registered ports. Ports 49,152 through 65,535 (0xFFFF) are used as temporary ports primarily by clients when communicating to servers.

Packet structure
UDP is a minimal message-oriented Transport Layer protocol that is documented in IETF RFC 768.

UDP provides no guarantees to the upper layer protocol for message delivery and the UDP protocol layer retains no state of UDP messages once sent. For this reason, UDP is sometimes referred to as Unreliable Datagram Protocol. UDP provides only application multiplexing (via port numbers) and integrity verification (via checksum) of the header and payload. If any kind of transmission reliability is needed, it must be implemented in the user's application. bits 0 32 64 0 - 15 Source Port Length Data 16 - 31 Destination Port Checksum

The UDP header consists of only 4 fields. The use of two of those is optional (pink background in table). Source port This field identifies the sending port when meaningful and should be assumed to be the port to reply to if needed. If not used, then it should be zero. Destination port This field identifies the destination port and is required. Length A 16-bit field that specifies the length in bytes of the entire datagram: header and data. The minimum length is 8 bytes since that's the length of the header. The field size sets a theoretical limit of 65,535 bytes (8 byte header + 65527 bytes of data) for a UDP datagram. The practical limit for the data length which is imposed by the underlying IPv4 protocol is 65,507 bytes. Checksum The 16-bit checksum field is used for error-checking of the header and data. The algorithm for computing the checksum is different for transport over IPv4 and IPv6.

Checksum computation
The method used to compute the checksum is defined in RFC 768: Checksum is the 16-bit one's complement of the one's complement sum of a pseudo header of information from the IP header, the UDP header, and the data, padded with zero octets at the end (if necessary) to make a multiple of two octets. In other words, all 16-bit words are summed using one's complement arithmetic. The sum is then one's complemented to yield the value of the UDP checksum field.

If the checksum calculation results in the value zero (all 16 bits 0) it should be sent as the one's complement (all 1's). The difference between IPv4 and IPv6 is in the data used to compute the checksum.

IPv4
When UDP runs over IPv4, the checksum is computed using a pseudo-header that contains information from the IPv4 header: bits 0 32 64 96 128 160 Zeros 0-7 8 - 15 16 - 23 24 - 31

Source address Destination address Protocol UDP length Destination Port Checksum Data Source Port Length

The source and destination addresses are those in the IPv4 header. The protocol is that for UDP (see List of IP protocol numbers): 17. The UDP length field is the length of the UDP header and data. UDP checksum computation is optional for IPv4. If a checksum is not used it should be set to the value zero.

IPv6
When UDP runs over IPv6, the checksum is mandatory. The method used to compute it is changed as documented in RFC 2460: Any transport or other upper-layer protocol that includes the addresses from the IP header in its checksum computation must be modified for use over IPv6 to include the 128-bit IPv6 addresses.

When computing the checksum, a pseudo-header is used that mimics the IPv6 header:

bits 0 32 64 96 128 160 192 224 256 288 320 352 384

0-7

8 - 15

16 - 23

24 - 31

Source address

Destination address

UDP length Zeros Source Port Length Data Next Header Destination Port Checksum

The source address is the one in the IPv6 header. The destination address is the final destination; if the IPv6 packet doesn't contain a Routing header, that will be the destination address in the IPv6 header; otherwise, at the originating node, it will be the address in the last element of the Routing header, and, at the receiving node, it will be the destination address in the IPv6 header. The value of the Next Header field is the protocol value for UDP: 17. The UDP length field is the length of the UDP header and data.

Comparison of UDP and TCP


Transmission Control Protocol is a connection-oriented protocol, which means that it requires handshaking to set up end-to-end communications. Once a connection is set up user data may be sent bi-directionally over the connection.

Reliable TCP manages message acknowledgment, retransmission and timeout. Many attempts to reliably deliver the message are made. If it gets lost along the way, the server will re-request the lost part. In TCP, there's either no missing data, or, in case of multiple timeouts, the connection is dropped. Ordered if two messages are sent over a connection in sequence, the first message will reach the receiving application first. When data segments arrive in the wrong order, TCP buffers the out-of-order data until all data can be properly re-ordered and delivered to the application. Heavyweight TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control.

Streaming Data is read as a byte stream, no distinguishing indications are transmitted to signal message (segment) boundaries.

UDP is a simpler message-based connectionless protocol. Connectionless protocols do not set up a dedicated end-to-end connection. Communication is achieved by transmitting information in one direction from source to destination without verifying the readiness or state of the receiver.

Unreliable When a message is sent, it cannot be known if it will reach its destination; it could get lost along the way. There is no concept of acknowledgment, retransmission and timeout. Not ordered If two messages are sent to the same recipient, the order in which they arrive cannot be predicted. Lightweight There is no ordering of messages, no tracking connections, etc. It is a small transport layer designed on top of IP. Datagrams Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent.

ADVANTAGES
1. Faster than TCP 2. Less overhead

DISADVANTAGES
1. Unreliable 2. Cannot be used for bulk data transfer 3. Connectionless

APPLICATIONS
1. Supports applications like RTP,SNMP. 2. Domain Name System (DNS). 3. streaming media applications such as IPTV, Voice over IP (VoIP), 4. Trivial File Transfer Protocol (TFTP) and many online games.

RELATED TEXT BOOKS


1.Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004. 2.James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3. Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4. Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5. William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000.

RELATED WEB LINKS


1.www.wikipedia.com 2.www.google.com 3.www.altavista.com 4.www.programmersheaven.com

Ex.no:2 Date:
AIM

CLIENT-SERVER CHAT USING UDP

To write a C program for implementing chat program using UDP.

ALGORITHM SERVER
Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_DGRAM as type. Step 3: Name the socket using bind( ) system call with the parameters server_sockfd and the server address(sin_addr and sin_sport). Step 4: The server gets the message from the client. Step 5: Prints the message. Step 6: Stop the program execution.

CLIENT
Step 1: Start the program. Step 2: Create an unnamed socket for client using socket Step 3: Call with parameters AF_INET as domain an SOCK_DGRAM as type. Step 4: Name the socket using bind( ) system call. Step 5: The Sendto( ) system call is used to deliver the Message to the server. Step 6: Stop the program execution.

CLIENT SERVER CHAT USING UDP SERVER


#include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> main() { struct sockaddr_in sadd,cadd; int id,a,b,len,port; char rbuff[100]; id=socket(PF_INET,SOCK_DGRAM,0); if(id<0) printf("Can't Create\n"); else printf("Created\n"); printf("Enter the port Address\n"); printf("____________________\n"); scanf("%d",&port); sadd.sin_family=PF_INET; sadd.sin_addr.s_addr=htonl(INADDR_ANY); sadd.sin_port=htons(port); b=bind(id,(struct sockaddr*)&sadd,sizeof(sadd)); if(b<0) printf("Can't Bind"); else printf("Binded\n"); printf("~~~~~~\n"); len=sizeof(cadd); if(recvfrom(id,rbuff,sizeof(rbuff),0,(struct sockaddr*)&cadd,&len)<0) printf("Received Error\n"); else printf("Server received =%s\n",rbuff); close(id); }

CLIENT
#include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> main() { struct sockaddr_in sadd,cadd; int id,len,n,c,s,b,port; char str[100],serstr[100]; id=socket(PF_INET,SOCK_DGRAM,0); if(id<0) printf("Can't Create\n"); else printf("Socket is Created\n"); printf("Enter the IP address\n"); scanf("%s",serstr); printf("Enter the port Address\n"); scanf("%d",&port); cadd.sin_family=PF_INET; cadd.sin_addr.s_addr=inet_addr(serstr); cadd.sin_port=htons(port); printf("Enter the Data\n"); scanf("%s",str); b=bind(id,(struct sockaddr*)&cadd,sizeof(cadd)); if(sendto(id,str,sizeof(str),0,(struct sockaddr*)&cadd,sizeof(cadd))<0) printf("Transmit Error"); else printf("Server Transmitted=%s\n",str); close(id); }

OUTPUT:
Client Side [1me16@localhost ~]$ cc udpclient.c [1me16@localhost ~]$. /a.out Socket is Created Enter the IP Address 172.15.170.104 Enter the port address 6543 Enter the data Hello Server transmitted = hello Server Side [1me16@localhost ~]$ cc udpserver.c [1me16@localhost ~]$. /a.out Created Enter the port address . 6543 Binded .

RESULT
Thus the C program for chat using UDP is executed and the output is verified successfully.

Ex. No. 3a Date:


AIM

PRINTING THE CLIENT ADDRESS AT THE SERVER END

To write a C program for printing the client address at the server end.

ALGORITHM SERVER
Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as type. Step 3: Name the socket using bind( ) system call with the parameters server_sockfd and the server address(sin_addr and sin_sport). Step 4: Create a connection queue and wait for clients using the listen( ) system call with the number of clients request as parameters. Step 5: Accept the connection using accept( ) system call when client requests for connection. Step 6: If the descriptor is less than zero,then the connection is not established and the stop the process. Step 7: Print the IP address sent by the client to the server. Step 8: Stop the program execution.

CLIENT
Step 1: Start the program. Step 2: Create an unnamed socket for client using socket( ) system. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type. Step 4: Name the socket using bind( ) system call. Step 5: Now connect the socket to server using connect( ) system call. Step 6: If the descriptor is less than zero, then the connection is not established. Step 7: If there is no connection,then terminate the process. Step 8: Else send the IP address to the server. Step 9: Stop the process.

PRINTING THE CLIENT ADDRESS AT THE SERVER END SERVER


#include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int sd,sd2,nsd,clilen,sport,len; char sendmsg[20],rcvmsg[20]; struct sockaddr_in servaddr,cliaddr; printf("Enter the Port\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=inet_addr("172.15.170.104"); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf(" Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); printf("The Client Address is %s",inet_ntoa(cliaddr.sin_addr.s_addr)); }

CLIENT
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],revmsg[20]; struct sockaddr_in servaddr; printf("Enter the port\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Scocket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=inet_addr("172.15.170.104"); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); }

OUTPUT:
Client Side [1me16@localhost ~]$ cc addressclient.c [1me16@localhost ~]$. /a.out Enter the port: 6543 Socket is Created... Server Side [1me16@localhost ~]$ cc addressserver.c [1me16@localhost ~]$. /a.out Enter the port: 6543 Created... Binded

RESULT
Thus the C program for printing the client IP Address at the server end is executed and the output is verified successfully.

Ex.no: 3b Date:
AIM

DATE-TIME SERVER

To write a C program for implementing the simple TCP client-server where the server acts as a Date-Time server.

ALGORITHM SERVER
Step 1 :Start the program Step 2 :Create an unnamed socket for the server using parameters AF_INET as domain and SOCK_STREAM as type. Step 3 : Declare the time variables t. Step 4 :Get the server port number. Step 5 :Register the host address to the system by using bind() system call in server side. Step 6 :Create a connection queue and wait for clients using listen() system call with The number of clients requests as parameter. Step 7 :Accept the connection using accept( ) system call when the client request for connection. Step 8 :Stop the Program execution.

CLIENT
Step 1 :Start the program. Step 2 :Create an unnamed socket for the client using parameters AF_INET as domain and SOCK_STREAM as type. Step 3 :Get the client port number. Step 4 :Now connect the socket to server using connect( ) system call. Step 5 :The recv() system call gets the response of Date-Time request from the server. Step 6 :Print the date and time Step 7 :Stop the program.

DISPLAYING TIME AT THE CLIENT END SERVER


#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<time.h> main() { int sd,sd2,nsd,clilen,sport,len; char sendmsg[20],rcvmsg[20]; time_t t; struct sockaddr_in servaddr,cliaddr; printf("Enter the Port no\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); time(&t); strcpy(sendmsg,ctime(&t)); printf("%s",sendmsg); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf(" Can't Bind\n"); else printf("\n Binded \n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); send(nsd,sendmsg,100,0); }

CLIENT
#include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdlib.h> #include<time.h> main() { int csd,cport,len; char revmsg[100]; struct sockaddr_in servaddr; printf("Enter the port\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Connection error\n"); recv(csd,revmsg,100,0); printf("%s\n",revmsg); }

OUTPUT:
Client Side [1me16@localhost ~]$ cc dateclient.c [1me16@localhost ~]$. /a.out Enter the port: 8543 Socket is Created... Connected Server Side [1me16@localhost ~]$ cc dateserver.c [1me16@localhost ~]$. /a.out Enter the port: 8543 Fri Sep 17 03:05:27 2010 Socket is Created...

RESULT
Thus the C program for printing Date and time is executed and the output is verified successfully.

Ex.no:3c Date:
AIM:

FILE TRANSFER USING TCP

To write a C program for transferring a file using TCP.

ALGORITHM:
SERVER: Step 1:Start the program. Step 2:Create an unnamed socket for the server using parameters AF_INET as domain and SOCK_STREAM as type. Step 3:Get the server port number. Step 4:Register the host address to the system by using bind() system call in server side. Step 5:Create a connection queue and wait for clients using listen() system call with the number of clients requests as parameter. Step 6:Create a Child process using fork( ) system call. Step 7:If the process identification number is equal to zero accept the connection using accept( ) system call when the client request for connection. Step 8:If pid is not equal to zero then exit the process. Step 9:Stop the Program execution. CLIENT: Step 1:Start the program. Step 2:Create an unnamed socket for the client using parameters AF_INET as domain and SOCK_STREAM as type. Step 3:Get the client port number. Step 4:Now connect the socket to server using connect( ) system call. Step 5:Enter the file name. Step 6:The file is transferred from client to server using send ( ) function. Step 7:Print the contents of the file in a new file. Step 8:Stop the program.

FILE TRANSFER PROTOCOL USING TCP SERVER


#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { FILE *fp; int sd,newsd,ser,n,a,cli,pid,bd,port,clilen; char name[100],fileread[100],fname[100],ch,file[100],rcv[100]; struct sockaddr_in servaddr,cliaddr; printf("Enter the port address: "); scanf("%d",&port); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(port); a=sizeof(servaddr); bd=bind(sd,(struct sockaddr*)&servaddr,a); if(bd<0) printf(" Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); newsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(newsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); n=recv(newsd,rcv,100,0); rcv[n]='\0'; fp=fopen(rcv,"r"); if(fp==NULL) {

send(newsd,"error",5,0); close(newsd); } else { while(fgets(fileread,sizeof(fileread),fp)) { if(send(newsd,fileread,sizeof(fileread),0)<0) { printf("Can't send\n"); } sleep(1); } if(!fgets(fileread,sizeof(fileread),fp)) { send(newsd,"completed",999999999,0); } return(0); } }

CLIENT
#include<stdio.h> #include<sys/socket.h> #include<netinet/in.h> main() { FILE *fp; int csd,n,ser,s,cli,cport,newsd; char name[100],rcvmsg[100],rcvg[100],fname[100]; struct sockaddr_in servaddr; printf("Enter the port"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) { printf("Error..."); exit(0); } else printf("Socket is Created...\n");

servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY);servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Error in Connection...\n"); else printf("Connected...\n"); printf("Enter the existing file name: "); scanf("%s",name); printf("\nEnter the new filename: "); scanf("%s",fname); fp=fopen(fname,"w"); send(csd,name,sizeof(name),0); while(1) { s=recv(csd,rcvg,100,0); rcvg[s]='\0'; if(strcmp(rcvg,"error")==0) printf("File is not Available...\n"); if(strcmp(rcvg,"completed")==0) { printf("file is transferred...\n"); fclose(fp); close(csd); break; } else fputs(rcvg,stdout); fprintf(fp,"%s",rcvg); } }

OUTPUT:
Server Side [1me16@localhost ~]$ cc ftpclient.c [1me16@localhost ~]$. /a.out Enter the port address: 8663 Socket is Created Binded Connected Client Side [1me16@localhost ~]$ cc ftpserver.c [1me16@localhost ~]$. /a.out Socket is Created.. Connected Enter the existing file name: net Enter the new file name: network Welcome to Network Lab File is transferred...

RESULT
Thus the C program for transferring file from one machine to another machine using TCP is executed and the output is verified successfully.

EX. NO. 4

SLIDING WINDOW PROTOCOL


Sliding Window Protocol

Sliding Window Protocols are a feature of packet-based data transmission protocols. They are used in the data link layer (OSI model) as well as in TCP (transport layer of the OSI model). They are used to keep a record of the frame sequences sent, and their respective acknowledgements received, by both the users. Their additional feature over a simpler protocol is that can allow multiple packets to be "in transmission" simultaneously, rather than waiting for each packet to be acknowledged before sending the next. In transmit flow control, sliding window is a variable-duration window that allows a sender to transmit a specified number of data units before an acknowledgment is received or before a specified event occurs. An example of a sliding window is one in which, after the sender fails to receive an acknowledgment for the first transmitted frame, the sender "slides" the window, i.e. resets the window, and sends a second frame. This process is repeated for the specified number of times before the sender interrupts transmission. Sliding window is sometimes (loosely) called acknowledgment delay period. For example, supposing a fixed window size of m frames, a sender may send out m frames () before receiving any acknowledgment. If acknowledgment arrives from the receiver for packet n, then the range (window) of unacknowledged frames slides to , and the sender is able to send out frame (n + m). In some way, "sliding" signifies a FIFO operation, trimming the range at one end, extending it at the other end. The purpose of the sliding window is to increase throughput. Let's denote the round trip time with RTT. The time necessary to transfer and acknowledge K (a big number of) packets is roughly (in one round trip, 2m frames and 2m ACKs are delivered). However, the size of the window (in bytes) should not grow above "capacity of the path" (the sum of affected network buffer sizes of all hops along the path): windows that are too big do not increase throughput; they only increase latency, the number of frames transmitted out-of-order, and memory usage. In practice, protocols often adapt the window size to the link's speed and actual saturation or congestion.

Concept
At any instant of time, the sender maintains a set of sequence numbers which correspond to the frames it is permitted to send. Such frames are said to be a set of the sending window. Similarly, the receiver also maintains a receiving window which indicates the set of frames it is allowed to receive.

A window can be visualized as a circle divided into (2n) 1 parts where n is the number of bits required to represent, in binary, the maximum sequence number in a given sequence of packets. The upper and lower edges of a sending window indicate the set of packets which are allowed to be sent but have not been acknowledged. The upper and lower edges of a receiving window indicate the set of packets it may accept. Whenever the network layer sends a new frame, the upper edge of the sending window is advanced by one. As shown in the figure, when a new frame is sent from the network layer to the data link layer, the upper edge of the window advances to 1 which indicates that the data link layer is allowed to send the 0th and 1st frames as they are still unacknowledged. On receiving the 0th frame the receiving window in the data link layer of the recipient advances its lower edge by one indicating it has received the 0th frame and the recipient sends an acknowledgement. On receiving the acknowledgement, the sending window advances its lower edge by one, indicating that the transmission and subsequent reception of the 0th frame is complete.

Sliding Window Algorithm


The sliding window algorithm works as follows: First, the sender creates a sequence number for each frame as it is transmitted. Throughout the communication, it maintains the send window size, the last acknowledgment received, and the last frame sent. To ensure that the window does not overflow, the sender ensures that the window size is greater than the sequence number of last frame sent minus the sequence number last acknowledgment received. When the sender transmits a frame, it increments the sequence number by one and starts a timer. The sequence number is sent with the frame so that the receiver can detect if a frame is received out of order. The sender continues sending frames until the buffer of unacknowledged frames is as large as the send window size. The sender then waits until it receives acknowledgments before transmitting more frames. Whenever the sender receives an acknowledgment from the receiver, it increments the value of the last acknowledgement received, thereby sliding the "sliding window" to the right. If the timer for the frame expires before the sender receives an acknowledgment for the frame, it assumes that the frame was lost and retransmits it. The receiver holds onto three pieces of information as well: the receive window size, the last frame received, and the next frame to acknowledge. When a frame arrives, the receiver evaluates the frame to determine if it falls within the receiver's window. The size of the receiver's window is determined by the number of frames the receiver can buffer before overflowing. The receiver cannot process frames received out of order. A frame is out of order if a gap exists between the sequence numbers of the newly received frame and that of the last frame received.

7 6 5 4

0 1

0 1

If a frame is received with a sequence number that results in a gap larger than the size of 2 the receiver's window, the frame is 2 determined to be outside the window and is discarded. If a frame is received with a sequence number that is lower than or equal to that of the 3 last frame received, this frame is by definition 3 outside the window and must be a 4 duplicate. It is also discarded. Packets with sequence numbers that fall within the window are accepted and put into the buffer. After accepting the frame, the receiver again checks the sequence number to determine if the frame was received in the correct order. The receiver compares the incoming frame's sequence number to next frame to acknowledge sequence number. If they match the receiver sends an acknowledgment. The next frame to acknowledge and last frame received are both incremented, thus sliding the window along. Frames which are within the window but arrived out of sequence remain in the buffer until the intervening frames in the sequence arrive .

Figure -1 shows an example with a maximum window size of 1. Initially, no frames are outstanding, so the lower and upper edges of the senders window are equal, but as time goes on, the situation progresses as shown.

SENDER 0 1 2 4 3 a) Initially

RECIEVER

7 b) After the First frame has Been sent 6 5 4 7 6 5 4 3 0 1 2

0 1 2 3

7 6 5 4 3

0 1 2 7 c) After the first Frame has Been received 6 5 4 3 0 1 2

7 6 5 4

0 1 d) After the first 2 3 Acknowledgement Has been received. 5 6

0 1 2 4 3

Variants There are three variants:


Stop-and-wait Go back n Selective repeat

STOP-AND-WAIT
Window size 1. Must get ack before can send next frame. Both machines are sending and receiving. Combined in one loop here. Let us assume one goes first. If both start simultaneously, get problem

GO BACK N (GBN)
Receiver B window size = 1 Discard all frames after error

No ack - they will eventually get re-sent Can be lot of re-sends Wastes lot of bandwidth if error rate high.

Acks may get lost/damaged. "ack n" is interpreted by A as "ack everything up to n". Each frame has its own timer.

SELECTIVE REPEAT (SR)


Receiver B window size = n Good frames after error are buffered (because can't send them to Network Layer NB yet, can't get rid of them) Bad frame 2 times out and is re-sent. At a timeout, sender A only sends the oldest un-ack-ed frame, not a sequence.

COMPARISON
If errors low, might use GBN. If errors high, might use SR. If bandwidth cheap, might use GBN. If bandwidth costly, might use SR. If memory costly at B, might use GBN. If memory cheap at B, might use SR.

NUMBERING FRAMES
Set aside n bits for frame number. There will be 2n distinct frame numbers, running 0 ... 2n - 1. Then loop round - re-use 0 ... 2n - 1 again.

LOST FRAMES
Must make sure that no more than 2n - 1 frames are un-ack-ed at any point, not 2 frames (even though there are 2n distinct frame numbers).
n

ADVANTAGES
Better usage of bandwidth using piggybacking. Easy to simulate multiple timers in software Faster than Stop & wait

DISADVANTAGES
Piggybacking technique is costlier to implement. SWP is complex than Stop and Wait

APPLICATIONS
To implement flow controlmechanisms in networks Used specifically for packet transmission & retransmission

RELATED TEXT BOOK 1. Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004.
2. James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3. Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4. Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5. William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000.

RELATED WEB LINKS


4. 5. 6. 7. www.wikipedia.com www.google.com www.altavista.com www.programmersheaven.com

EX.NO:4 DATE:
AIM

SIMULATION OF SLIDING WINDOW PROTOCOL

To write a C program for the simulation of Sliding Window Protocol.

ALGORITHM SENDER
Step 1: Start the program. Step 2: Create a Socket for the Sender and bind it with the receiver. Step 3: Set the size of the window. Step 4: Send the frames upto the size of the window to the receiver Step 5: If any of the frames are lost then retransmit those frames to the receiver Step 6: Stop the execution.

RECEIVER
Step 1: Start the program. Step 2: Create the Socket for the Receiver, bind it and listen for the frames from the sender. Step 3: If all the frames are successfully received, send the acknowledgement for the last frame to the sender. Step 4: If any of the frames is lost, then send the acknowledgement of the last frame, which was successfully received. Step 5: Keep on receiving and acknowledging the frames until the sender sends. Step 6: Stop the program execution.

SLIDING WINDOW PROTOCOL


SERVER
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> main() { int a,bd,sd,newsd,port,clilen; char lost[20],sendmsg[20],recvmsg[20]; struct sockaddr_in servaddr,cliaddr; sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); printf("Enter the port no\n"); scanf("%d",&port); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(port); a=sizeof(servaddr); bd=bind(sd,(struct sockaddr*)&servaddr,a); if(bd<0) printf(" Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); newsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(newsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); printf("Enter the lost frame\n"); scanf("%s",lost); send(newsd,lost,20,0); recv(newsd,recvmsg,20,0);

printf("\n Frame %s is successfully received",recvmsg); }

CLIENT
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,n,port; char sendmsg[100],recvmsg[100]; struct sockaddr_in servaddr; printf("Enter the port\n"); scanf("%d",&port); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create\n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(port); if(connect(sd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); printf("Enter the no of frames\n"); scanf("%d",&n); printf("\nThe frames all\n"); for(i=1;i<=n;i++) printf("Frame %d\n",i); recv(sd,recvmsg,20,0); printf("\n Lost frame %s is retransmitted ",recvmsg); strcpy(sendmsg,recvmsg); send(sd,sendmsg,20,0); }

OUTPUT:
Server: [1me16alhost~]: VI swserver.c [1me16alhost~]: CC swserver.c [1me16alhost~]: /a.out Enter the port address 8543 Socket is created Binded Accepted Enter the lost frame: 3 Frame tcpserver.c is successfully transmitted Client: [1me16alhost~]: VI swclient.c [1me16alhost~]: CC swclient.c [1me16alhost~]: /a.out Enter the client port no 8543 Socket is created Connected.. Enter the no of frames: 4 The frames all Frame 1/n Frame 2/n Frame 3/n Frame 4/n

RESULT

Thus the C program for the simulation of Sliding Window Protocol has been executed and the output is verified successfully.

Development of applications EX. NO. 5


INTRODUCTION
The Domain Name System (DNS) associates various information with domain names; most importantly, it serves as the "phone book" for the Internet by translating human-readable computer hostnames, e.g. www.example.com, into IP addresses, e.g. 208.77.188.166, which networking equipment needs to deliver information. It also stores other information such as the list of mail servers that accept email for a given domain. In providing a worldwide keywordbased redirection service, the Domain Name System is an essential component of contemporary Internet use.

DOMAIN NAME SYSTEM

THE DOMAIN NAME SPACE


The domain name space consists of a tree of domain names. Each node or leaf in the tree has zero or more resource records, which hold information associated with the domain name. The tree sub-divides into zones beginning at the root zone. A DNS zone consists of a collection of connected nodes authoritatively served by an authoritative DNS nameserver. (Note that a single nameserver can host several zones). When a system administrator wants to let another administrator control a part of the domain name space within the first administrators zone of authority, control can be delegated to the second administrator. This splits off a part of the old zone into a new zone, which comes under the authority of the second administrator's nameservers. The old zone ceases to be authoritative for the new zone.

PARTS OF A DOMAIN NAME


A domain name usually consists of two or more parts (technically a label), which is conventionally written separated by dots, such as example.com.

The rightmost label conveys the top-level domain (for example, the address www.example.com has the top-level domain com).

Each label to the left specifies a subdivision, or subdomain of the domain above it. Note: subdomain expresses relative dependence, not absolute dependence. For example: example.com comprises a subdomain of the com domain, and www.example.com comprises a subdomain of the domain example.com. In theory, this subdivision can go down 127 levels. Each label can contain up to 63 characters. The whole domain name does not exceed a total length of 253 characters. In practice, some domain registries may have shorter limits. A hostname refers to a domain name that has one or more associated IP addresses; ie: the 'www.example.com' and 'example.com' domains are both hostnames, however, the 'com' domain is not.

DNS SERVERS
The Domain Name System consists of a hierarchical set of DNS servers. Each domain or subdomain has one or more authoritative DNS servers that publish information about that domain and the name servers of any domains "beneath" it. The hierarchy of authoritative DNS servers matches the hierarchy of domains. At the top of the hierarchy stand the root nameservers: the servers to query when looking up (resolving) a top-level domain name (TLD).

DNS RESOLVERS
A resolver looks up the resource record information associated with nodes. A resolver knows how to communicate with name servers by sending DNS queries and heeding DNS responses.A DNS query may be either a recursive query or a non-recursive query: A non-recursive query is one where the DNS server may provide a partial answer to the query (or give an error). DNS servers must support non-recursive queries. A recursive query is one where the DNS server will fully answer the query (or give an error). DNS servers are not required to support recursive queries.

The resolver (or another DNS server acting recursively on behalf of the resolver) negotiates use of recursive service using bits in the query headers. Resolving usually entails iterating through several name servers to find the needed information. However, some resolvers function simplistically and can communicate only with a single name server. These simple resolvers rely on a recursive query to a recursive name server to perform the work of finding information for them.

ADDRESS RESOLUTION MECHANISM

In theory a full host name may have several name segments, (e.g ahost.ofasubnet.ofabiggernet.inadomain.example). In practice, in the experience of the majority of public users of Internet services, full host names will frequently consist of just three segments (ahost.inadomain.example, and most often www.inadomain.example). For querying purposes, software interprets the name segment by segment, from right to left, using an iterative search procedure. At each step along the way, the program queries a corresponding DNS server to provide a pointer to the next server which it should consult. The local system is pre-configured with the known addresses of the root servers in a file of root hints, which need to be updated periodically by the local administrator from a reliable source to be kept up to date with the changes which occur over time. Query one of the root servers to find the server authoritative for the next level down (so in the case of our simple hostname, a root server would be asked for the address of a server with detailed knowledge of the example top level domain). Querying this second server for the address of a DNS server with detailed knowledge of the second-level domain (inadomain.example in our example). Repeating the previous step to progress down the name, until the final step which would, rather than generating the address of the next DNS server, return the final address sought.

ADVANTAGES
Since DNS stores records in hierarchical manner large number of IP address can be stored . IP address can be easily searched.

DISADVANTAGE Hierarchical storage is very complex in nature and occupies more space.

APPLICATIONS
Hostnames and IP addresses do not necessarily match on a one-to-one basis. Many hostnames may correspond to a single IP address: combined with virtual hosting, this allows a single machine to serve many web sites. Alternatively a single hostname may correspond to many IP addresses: this can facilitate fault tolerance and load distribution, and also allows a site to move physical location seamlessly. There are many uses of DNS besides translating names to IP addresses. For instance, Mail transfer agents use DNS to find out where to deliver e-mail for a particular address.

The domain to mail exchanger mapping provided by MX records accommodates another layer of fault tolerance and load distribution on top of the name to IP address mapping. Sender Policy Framework and DomainKeys instead of creating their own record types were designed to take advantage of another DNS record type, the TXT record. To provide resilience in the event of computer failure, multiple DNS servers are usually provided for coverage of each domain, and at the top level, thirteen very powerful root servers exist, with additional "copies" of several of them distributed worldwide via Anycast.

RELATED TEXT BOOKS


1. Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004. 2. James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3. Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4. Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5. William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000.

RELATED WEB LINKS


1. 2. 3. 4. www.wikipedia.com www.google.com www.altavista.com www.programmersheaven.com

EX.NO:5 DATE:
AIM

DOMAIN NAME SYSTEM

To write a C program for the simulation of Domain Name System

ALGORITHM SERVER
Step 1: Start the program. Step 2: Create the Socket for the Server. Step 3: Bind the Socket to the Port. Step 4: Listen for the incoming client connection. Step 5: Receive the IP address from the client to be resolved. Step 6: Get the domain name from the client. Step 7: Check the existence of the domain in the server. Step 8: If domain matches then send the corresponding address to the client. Step 9: Stop the program execution.

CLIENT
Step 1: Start the program. Step 2: Create the Socket for the client. Step 3: Connect the Socket to the server. Step 4: Send the hostname to the server to be resolved. Step 5: If the server responds the print the address and terminates the process.

DOMAIN NAME SYSTEM


SERVER
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int sd,sd2,nsd,clilen,sport,len,i; char sendmsg[20],recvmsg[20]; char ipid[20][20]={"172.15.64.66","172.15.44.55","172.15.33.44","172.15.22.33"}; char hostid[20][20]={"www.yahoo.com","www.google.com","www.hotmail.com"}; struct sockaddr_in servaddr,cliaddr; printf("DNS Server Side\n"); printf("Enter the Port\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf("Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); recv(nsd,recvmsg,20,0); for(i=0;i<4;i++) {

if(strcmp(recvmsg,hostid[i])==0) { send(nsd,ipid[i],20,20); break; }}}

CLIENT
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],recvmsg[20]; struct sockaddr_in servaddr; printf("DNS Client Side\n"); printf("Enter the Client port\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); printf("Enter the host address\n"); scanf("%s",sendmsg); send(csd,sendmsg,20,0); recv(csd,recvmsg,20,20); printf("The Coresponding IP Address is\n"); printf("%s",recvmsg); }

OUTPUT:
Server: [1me16alhost~]: VI dnsserver.c [1me16alhost~]: CC dnsserver.c [1me16alhost~]: /a.out Enter the port no 8543 Socket is created Binded Accepted Client: [1me16alhost~]: VI dnsclient.c [1me16alhost~]: CC dnsclient.c [1me16alhost~]: /a.out Enter the client port no 8543 Socket is created Connected.. Enter the host address www.yahoo.com The corresponding IP Address is 172.15.64.66

RESULT

Thus the C program for the simulation of Domain Name System has been executed and the output is verified successfully.

EX. N0. 5

ROUTING PROTOCOL

A routing protocol is a protocol that specifies how routers communicate with each other, disseminating information that enables them to select routes between any two nodes on a computer network, the choice of the route being done by routing algorithms. Each router has a prior knowledge only of networks attached to it directly. A routing protocol shares this information first among immediate neighbors, and then throughout the network. This way, routers gain knowledge of the topology of the network. For a discussion of the concepts behind routing protocols, see: Routing. The term routing protocol may refer specifically to one operating at layer three of the OSI model, which similarly disseminates topology information between routers. Many routing protocols used in the public Internet are defined in documents called RFCs. Although there are many types of routing protocols, two major classes are in widespread use in the Internet: link-state routing protocols, such as OSPF and IS-IS; and path vector or distance vector protocols, such as BGP, RIP and EIGRP. The specific characteristics of routing protocols include:

The manner in which they either prevent routing loops from forming or break them up if they do. The manner in which they select preferred routes, using information about hop costs. The time they take to converge. How well they scale up. Many other factors.

Routed versus routing protocols


Confusion often arises between routing protocols and routed protocols. While routing protocols help the router decide which paths to send traffic along, routed protocols are responsible for the actual transfer of traffic between devices running L3 protocols such as IP.Specifically, a routed protocol is any network protocol that provides enough information in its network layer address to allow a packet to be forwarded from one host to another based on the addressing scheme, without knowing the entire path from source to destination. Routed protocols define the format and use of the fields within a packet. Packets generally are conveyed from end system to end system. Almost all layer 3 protocols, and those that are layered over them, are routable, with IP being an example. Layer 2 protocols such as Ethernet are necessarily non-routable protocols, since they contain only a link-layer address, which is insufficient for routing: some higher-level protocols based directly on these without the addition of a network layer address, such as NetBIOS, are also non-routable.

In some cases, routing protocols can themselves run over routed protocols: for example, BGP runs over TCP which runs over IP; care is taken in the implementation of such systems not to create a circular dependency between the routing and routed protocols. That a routing protocol runs over particular transport mechanism does not mean that the routing protocol is of layer (N+1) if the transport mechanism is of layer (N). Routing protocols, according to the OSI Routing framework, are layer management protocols for the network layer, regardless of their transport mechanism: IS-IS runs over the data link layer. OSPF, IGRP, and EIGRP run directly over IP; OSPF and EIGRP have their own reliable transmission mechanism while IGRP assumed an unreliable transport. RIP runs over UDP. BGP runs over TCP.

Examples Interior routing protocols


Interior Gateway Protocols (IGPs) exchange routing information within a single routing domain. A given autonomous system [6] can contain multiple routing domains, or a set of routing domains can be coordinated without being an Internet-participating autonomous system. Common examples include:fh

IGRP (Interior Gateway Routing Protocol) EIGRP (Enhanced Interior Gateway Routing Protocol) OSPF (Open Shortest Path First) RIP (Routing Information Protocol) IS-IS (Intermediate System to Intermediate System)

Note that IGRP, a Cisco proprietary routing protocol, is no longer supported. EIGRP accepts IGRP configuration commands, but the internals of IGRP and EIGRP are completely different.

Open Shortest Path First Routing Protocol


Open Shortest Path First (OSPF) is a robust link-state interior gateway protocol (IGP). People use OSPF when they discover that Routing Information Protocol (RIP) just isnt going to work for their larger network, or when they need very fast convergence. OSPF is the most widely used IGP. When we discuss IGPs, were talking about one routing domain, or Autonomous System (AS). Imagine a medium-sized company with multiple buildings and departments, all connected and sharing two redundant Internet links. All of the buildings on-site are part of the same AS. With OSPF, however, we also have the concept of an Area, which allows further segmentation, perhaps by department in each branch. To understand the design needs for areas in OSPF, lets start with discussing how OSPF works. There is some terminology you may not have encountered before, including the following:

Router ID: In OSPF this is a unique 32-bit number assigned to each router. This is chosen as the highest IP address on a router, and can be set large by configuring an address on a loopback interface of the chosen router. Neighbor Routers: two routers with a common link that can talk to each other. Adjacency: a two-way relationship between two neighbor routers. Neighbors dont always form adjacencies. LSA: Link State Advertisements are flooded; they describe routes within a given link. Hello Protocol: This is how routers on a network determine their neighbors and form LSAs. Area: a hierarchy. A set of routers that exchange LSAs, with others in the same area. Areas limit LSAs and encourage aggregate routes.

OSPF is a link-state routing protocol, as weve said. Think of this as a distributed map of the network. To get this information distributed, OSPF does three things. First, when a router running OSPF comes up it will send hello packets to discover its neighbors and elect a designated router. The hello packet includes link-state information, as well as a list of neighbors. Providing information about your neighbor to that neighbor serves as an ACK, and proves that communication is bi-directional. OSPF is smart about the layer 2 topology: if youre on a point-to-point link, it knows that this is enough, and the link is considered up. If youre on a broadcast link, the router must wait for an election before deciding if the link is operational. The election ballot can be stuffed, with a Priority ID, so that you can ensure that your beefiest router is the Designated Router (DR). Otherwise, the largest IP address wins. The key idea with a DR and backup DR (BDR) is that they are the ones to generate LSAs, and they must do database exchanges with other routers in the subnet. So, nondesignated routers form adjacencies with the DR. The whole DR/BDR design is used to keep the protocol scalable. The only way to ensure that all routers have the same information is to make them synchronize their databases. If you have 21 routers, and want to bring another one up, then youd have to form 21 new adjacencies. If you centralize the database, with a backup (just in case), then adding more becomes an easy to manage linear problem. The database exchange is part of bringing up adjacencies after the hello packets are exchanged, and its very important. If the databases are out of sync, we could risk routing loops, blackholes and other perils. The third part of bringing up an adjacency is Reliable Flooding, or LSA exchange. The LSA area zero is special, and if you have multiple areas, they must all touch area zero. This is also called the Backbone Area. There are different types of areas in OSPF, and it can get really crazy when you throw in Virtual Links to allow two areas to speak without hitting area zero. There also are different types of routers in OSPF:

ABR: An Area Border Router is a router that is in area zero, and one or more other areas. DR, BDR: A Designated Router, as we said, is the router that keeps the database for the subnet. It sends and receives updates (via multicast) from the other routers in the same network. ASBR: The Autonomous System Boundary Router is very special, but confusing. The ASBR connects one or more AS, and exchanges routes between them. The ASBRs purpose is to redistribute routes from another AS into its own AS.

The concept of redistribution finally rears its head: lets say we have a router, an internal-only router, not a BR, and we want to connect it to a new network that we dont control. After this connection is made, we have a few options. We can fire up a non-IGP routing protocol, like BGP, to exchange routes. Alternatively, we could decide that a summary route is good enough, and hard-code a static route to the new network in this router. Anything directly using this router for this destination would be able to get to the new network, but OSPF doesnt know about it. To make that happen, we redistribute the miscellaneous information into OSPF. We wouldnt want to feed 200K+ routes from BGP into OSPF, but if we went the static route, wed definitely want to propagate that information so everyone in our AS could get to the new place. As soon as we tell our internal router that it should redistribute static routes into OSPF, it becomes an ASBR, and the entire network can now reach the new network. OSPF is perhaps the most widely-used IGP in large enterprise networks; IS-IS is more common in large service provider networks. The most widely-used exterior gateway protocol (EGP) is BGP.

DIJKSTRA'S ALGORITHM
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1959 is a graph search algorithm that solves the single-source shortest path problem for a graph with non negative edge path costs, outputting a shortest path tree. This algorithm is often used in routing. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.

RELATED SYNTAX

In the following algorithm, u := extract_min(Q) searches for the vertex u in the vertex set Q that has the least dist[u] value. That vertex is removed from the set Q and returned to the user. length(u, v) calculates the length between the two neighbor-nodes u and v. alt on line 10 is the length of the path from the root node to the neighbor node v if it were to go through u. If this path is shorter than the current shortest path recorded for v, that current path is replaced with this alt path. The previous array is populated with a pointer to the "next-hop" node on the source graph to get the shortest route to the source. 1 function Dijkstra(Graph, source): 2 for each vertex v in Graph: // Initializations 3 dist[v] := infinity // Unknown distance function from source to v 4 previous[v] := undefined 5 dist[source] := 0 // Distance from source to source 6 Q := copy(Graph) // All nodes in the graph are unoptimized - thus are in Q 7 while Q is not empty: // The main loop 8 u := extract_min(Q) // Remove and return best vertex from nodes in two given nodes // we would use a path finding algorithm on the new graph, such as depth-first search. 9 for each neighbor v of u: // where v has not yet been removed from Q. 10 alt := dist[u] + length(u, v) 11 if alt < dist[v] // Relax (u,v) 12 dist[v] := alt 13 previous[v] := u 14 return previous[] If we are only interested in a shortest path between vertices source and target, we can terminate the search at line 9 if u = target. Now we can read the shortest path from source to target by iteration: 1 S := empty sequence 2 u := target 3 while defined previous[u] 4 insert u at the beginning of S 5 u := previous[u] Now sequence S is the list of vertices constituting one of the shortest paths from source to target, or the empty sequence if no path exists.

RELATED EXERCISE

BELLMEN FORD ALGORITHM Simulation of Bellman Ford Routing algorithm with 7 nodes.
Possible node Routing Diagrams Step 1 : red arrows point to nodes reachable (immeidate neighbour) within 1 hop from the inspected node (Blue node). The distance from the start node to: b=1, c=1, e=1, f=1. Node b has the minimum distance. Any other path to b visits another red node, and will be longer than 1. Node b will be colored orange to indicate 1 is the length of the shortest path to b.

Step 2: Red arrows point to neighbour nodes that reachable from neighbour of inspected node that already have a final distance. The distance to: c=1, e=1, f=1. Node c has the minimum distance. There are no other arrows coming in to c. Node c will be colored orange to indicate 1 is the length of the shortest path to c.

Step 3: Red arrows point to neighbour nodes that reachable from neighbour of inspected node

that already have a final distance. The distance to: e=1, f=1. Node e has the minimum distance. There are no other arrows coming in to e. Node e will be colored orange to indicate 1 is the length of the shortest path to e.

Step 4: Red arrows point to neighbour nodes that reachable from neighbour of inspected node that already have a final distance. The distance to: f=1. Since this node forms a 'bridge' to the remaining nodes, all other paths to this node will be longer. Node f will be colored orange to indicate 1 is the length of the shortest path to f.

Step 5: Red arrows point to neighbour nodes that reachable from neighbour of inspected node that already have a final distance. The distance to: d=2, g=2. Node d has the minimum distance. Any other path to d visits another red node, and will be longer than 2. Node d will be colored orange to indicate 2 is the length of the shortest path to d.

Step 6: Red arrows point to neighbour nodes that reachable from neighbour of inspected node that already have a final distance. The distance to: g=2. There are no other arrows coming in to g. Node g will be colored orange to indicate 2 is the length of the shortest path to g.

Final Step: Follow the RED path from the start node to get the shortest path to the destination node. The length of the path is written in node.

DV is given in Table.

A B C D E F G

A 1A 1A 2F 1A 1A 2F

B 1B 1B 3F 2E 2F 4D

C 1C 1C 3F 2E 2F 4D

D 2F 3B 3C 3E 1D 2F

E 1E 2B 2C 3F 2F 4D

F 1F 2B 2C 1F 2E 2D

G 2F 3B 3C 2F 3E 2D -

Advantages of OSPF

OSPF is an open standard, not related to any particular vendor. OSPF is hierarchical routing protocol, using area 0 (Autonomous System) at the top of the hierarchy. OSPF uses Link State Algorithm, and an OSPF network diameter can be much larger than that of RIP. OSPF supports Variable Length Subnet Masks (VLSM), resulting in efficient use of networking resources. OSPF uses multicasting within areas. After initialization, OSPF only sends updates on routing table sections which have changed, it does not send the entire routing table, which in turn conserves network bandwidth. Using areas, OSPF networks can be logically segmented to improve administration, and decrease the size of routing tables.

Disadvantages of OSPF:
OSPF is very processor intensive due to implementation of SPF algorithm. OSPF maintains multiple copies of routing information, increasing the amount of memory needed. OSPF is a more complex protocol to implement compared to RIP.

Applications:
OSPF was the first widely deployed routing protocol that could converge a network in the low seconds, and guarantee loop-free paths. It has a great many features that allow the imposition of policies about the

propagation of routes that it may be appropriate to keep local, for load sharing, As mentioned, OSPF can provide better load-sharing on external links than other IGPs. When the default route to an ISP is injected into OSPF from multiple ASBRS as a Type I external route and the same external cost specified, other routers will go to the ASBR with the least path cost from its location.

RELATED TEXT BOOKS


1. Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004. 2. James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3. Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4. Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5. William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000. 6. INTERNET PROTOCOL, RFC 791, J Postel, September 1981. 7. BROADCASTING INTERNET DATAGRAMS IN THE PRESENCE OF SUBNETS, RFC 922, Jeffrey Mogul, October 1984 8. Towards Requirements for IP Routers, RFC 1716, P. Almquist, November 1994 9. Requirements for IP Version 4 Routers, RFC 1812, F. Baker,June 1995 10. Routing and Routed Protocols 11. Guidelines for creation, selection, and registration of an Autonomous System (AS), RFC 1930, J. Hawkison & T. Bates, March1996

RELATED WEB LINKS


1. 2. 3. 4. 5. www.wikipedia.com www.google.com www.altavista.com www.programmersheaven.com "http://en.wikipedia.org/wiki/Routing_protocol

EX.NO:6 DATE:
AIM

SIMULATION OF ROUTING PROTOCOLS

To Simulate Shortest Path Routing Algorithm

ALGORITHM

Step 1: Start the Program Step 2: Create a distance list, a previous vertex list, a visited list, and a current vertex. Step 3: All the values in the distance list are set to infinity except the starting vertex which is set to zero. Step 4: All values in visited list are set to false. Step 5: All values in the previous list are set to a special value signifying that they are undefined. Step 6: Current node is set as the starting vertex. Step 7: Mark the current vertex as visited. Step 8: Update distance and previous lists based on those vertices which can be immediately reached from the current vertex. Step 9: Update the current vertex to the unvisited vertex that can be reached by the shortest path from the starting vertex. Step 10: Repeat (from step 6) until all nodes are visited. Step 11: Stop the program execution.

SIMULATION OF OSPF ROUTING PROTOCOL


#include<iostream.h> #include<conio.h> class dij { private: int graph[15][15],source,no; int set[15],predessor[15],mark[15],pathestimate[15];

public: int minimum(); void read(); void initialize(); void printpath(int); void algorithm(); void output(); }; void dij::read() { cout<<"Enter the no of vertices: "; cin>>no; cout<<"Enter the Adjacent matrices"; for(int i=1;i<=no;i++) { cout<<"Enter the weight for row: "<<i; for(int j=1;j<=no;j++) { cin>>graph[i][j]; } } cout<<"Enter the source Vector: "; cin>>source; } void dij::initialize() { for(int i=1;i<=no;i++) { mark[i]=0; pathestimate[i]=999; predessor[i]=0; } pathestimate[source]=0; } void dij::algorithm() { initialize(); int count=0,i,u; while(count<no) { u=minimum(); set[++count]=u;

mark[u]=1; for(int i=1;i<=no;i++) { if(graph[u][i]>0) { if(mark[i]!=1) { if(pathestimate[i]>pathestimate[u]+graph[u][i]) { predessor[i]=u; pathestimate[i]=pathestimate[u]+graph[u][i]; } } } } //for loop } //while loop } void dij::printpath(int i) { cout<<endl; if(i==source) { cout<<source; } else if(predessor[i]==0) cout<<"No path from"<<source<<"to"<<i; else { printpath(predessor[i]); cout<<"....."<<i; } } void dij::output() { for(int i=1;i<=no;i++) { printpath(i); if(pathestimate[i]!=999) cout<<"->("<<pathestimate[i]<<")\n"; } cout<<endl; } int dij::minimum() {

int min=999,i,t; for(i=1;i<=no;i++) { if(mark[i]!=1) { if(min>=pathestimate[i]) { min = pathestimate[i]; t=i; } } } return t; } void main() { clrscr(); dij d; d.read(); d.algorithm(); d.output(); getch(); }

OUTPUT
Enter the no of vertices: 3 Enter the Adjacent matrices Enter the weight for row: 1 0 1 3 Enter the weight for row: 2

2 1 1 Enter the weight for row: 3 2 1 1 Enter the source vector: 1 1 -> (0) 1. 2- > (1) 1 2 . 3 -> (1)

RESULT:
Thus the Program for simulating Shortest Path Routing Algorithm is executed and the output is verified successfully.

EX. NO. 7

Hyper Text Transfer Protocol (HTTP)

Introduction to the HTTP protocol


Since 1990 HTTP protocol (HyperText Transfer Protocol) has been the most widely used protocol on the Internet. Version 0.9 was only intended to transfer data over the Internet (in particular Web pages written in HTML. Version 1.0 of the protocol (the most used) now allows the transfer of messages with headers describing the content of the message by using MIME type coding.

The aim of HTTP protocol is to allow transfer of files (essentially in HTML format) between a browser (the client) and a Web server (called among other things httpd on UNIX machines) located using a character string called a URL.

Communication between browser and server


Communication between the browser and server takes place in two stages:

The navigator makes a HTTP request The server processes the request then sends a HTTP response In reality, the communication is conducted in more stages if you consider the processing of the request by the server. Given that we are only concerned with HTTP protocol, server side processing will not be explained as part of this article.

HTTP Request
A HTTP request is a collection of lines sent to the server by the browser. It includes:

A request line: This is a line specifying the type of document requested, the method which must be applied, and the version of the protocol used. The line is made up of three elements which must be separated by a space: The method The URL The version of the protocol used by the client (generally HTTP/1.0)

The request header fields: This is a collection of optional lines allowing additional information about the request and/or the client to be given (browser, operating system, etc.). Each of these lines is composed of a name describing the header type, followed by a colon (:) and the value of the header The body of the request: This is a collection of optional lines which must be separated from preceding lines by an empty line and for example allowing data to be sent by a POST command during the sending of data to the server using a form

A HTTP request therefore has the following syntax (<crlf> meaning carriage return and line feed): METHOD URL VERSION<crlf> HEADER: Value<crlf> . . .HEADER: Value<crlf> Empty line <crlf> BODY OF THE REQUEST Here is an example of a HTTP request: GET http://en.kioskea.net/ HTTP/1.0 Accept: text/html If-Modified-Since: Saturday, 15-January-2000 14:37:11 GMT User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows 95)

Commands
Command Description GET HEAD POST PUT Request for the resource located at the specified URL Request for the header of the resource located at the specified URL Sends data to the program located at the specified URL Sends data to the specified URL

DELETE Deletes the resource located at the specified URL

HTTP Response
A HTTP response is a collection of lines sent to the server by the browser. It includes: A status line: this is a line specifying the protocol version used and the status of the request being processed using a code and explanatory text. The line is made up of three elements which must be separated by a space:

The version of the protocol used. The status code. The meaning of the code. The response header fields: This is a collection of optional lines allowing additional information about the response and/or the client to be given (browser, operating system, etc.). Each of these lines is composed of a name describing the header type, followed by a colon (:) and the value of the header. The body of the response: contains the requested document. A HTTP response therefore has the following syntax (<crlf> meaning carriage return and line feed): VERSION-HTTP CODE EXPLANATION<crlf> HEADER: Value<crlf> . . . HEADER: Value<crlf> Empty line <crlf> BODY OF THE RESPONSE Here is an example of a HTTP response: HTTP/1.0 200 OK Date: Sat, 15 Jan 2000 14:37:12 GMT Server: Microsoft-IIS/2.0 Content-Type: text/HTML Content-Length: 1245 Last-Modified: Fri, 14 Jan 2000 08:25:13 GMT

URL
URL is used to access HTML pages from the Web.It's often easiest, although not entirely accurate, to think of a URL as the name of a file on the World Wide Web because most URLs refer to a file on some machine on the network. However, remember that URLs also can point to other resources on the network, such as database queries and command output.

Host Name Filename Port Number Reference

The name of the machine on which the resource lives. The pathname to the file on the machine. The port number to which to connect (typically optional). A reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional).

For many protocols, the host name and the filename are required, while the port number and reference are optional. For example, the resource name for an HTTP URL must specify a server on the network (Host Name) and the path to the document on that machine (Filename); it also can specify a port number and a reference.

RELATED SYNTAX CREATING A URL


The easiest way to create a URL object is from a String that represents the humanreadable form of the URL address. This is typically the form that another person will use for a URL. For example, the URL for the Gamelan site, which is a directory of Java resources, takes the following form: http://www.gamelan.com/ URL gamelan = new URL("http://www.gamelan.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question. You can also create URL objects from a relative URL address.

CREATING A URL RELATIVE TO ANOTHER


A relative URL contains only enough information to reach the resource relative to (or in the context of) another URL. Relative URL specifications are often used within HTML files. For example, suppose you write an HTML file called JoesHomePage.html. Within this page, are links to other pages, PicturesOfMe.html and MyKids.html, that are on the same machine and in the same directory as JoesHomePage.html. The links to PicturesOfMe.html and MyKids.html from JoesHomePage.html could be specified just as filenames, like this: <a href="PicturesOfMe.html">Pictures of Me</a> <a href="MyKids.html">Pictures of My Kids</a>

These URL addresses are relative URLs. For example, http://www.gamean.com/pages/Gamelan.game.html http://www.gamelan.com/pages/Gamelan.net.html URL gamelan = new URL("http://www.gamelan.com/pages/"); URL gamelanGames = new URL(gamelan, "Gamelan.game.html"); URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html"); The URL constructor that lets you create a URL object from another URL object (the base) and a relative URL specification. The general form of this constructor is: URL(URL baseURL, String relativeURL) The first argument is a URL object that specifies the base of the new URL. The second argument is a String that specifies the rest of the resource name relative to the base. If baseURL is null, then this constructor treats relativeURL like an absolute URL specification. Conversely, if relativeURL is an absolute URL specification, then the constructor ignores baseURL. This constructor is also useful for creating URL objects for named anchors (also called references) within a file. For example, suppose the Gamelan.network.html file has a named anchor called BOTTOM at the bottom of the file. You can use the relative URL constructor to create a URL object for it like this: URL gamelanNetworkBottom = new URL(gamelanNetwork, "#BOTTOM");

OTHER URL CONSTRUCTORS


The URL class provides two additional constructors for creating a URL object. These constructors are useful when working with URLs, such as HTTP URLs, that have host name, filename, port number, and reference components in the resource name portion of the URL. These two constructors are useful when it does not have a String containing the complete URL specification, but it do new URL("http", "www.gamelan.com", "/pages/Gamelan.net.html");

This is equivalent to new URL("http://www.gamelan.com/pages/Gamelan.net.html"); The first argument is the protocol, the second is the host name, and the last is the pathname of the file. Note that the filename contains a forward slash at the beginning. This indicates that the filename is specified from the root of the host.

The final URL constructor adds the port number to the list of arguments used in the previous constructor: URL gamelan = new URL("http", "pages/Gamelan.network.html"); "www.gamelan.com", 80,

This creates a URL object for the following URL: http://www.gamelan.com:80/pages/Gamelan.network.html

URL ADDRESSES WITH SPECIAL CHARACTERS


Some URL addresses contain special characters, for example the space character. Like this: http://foo.com/hello world/ To make theses characters legal they need to encoded before passing them to the URL constructor. URL url = new URL("http://foo.com/hello%20world"); Encoding the special character(s) in this example is easy as there is only one character that needs encoding, but for URL addresses it is very difficult. Use the multi-argument constructors of the java.net.URI class to automatically take care of the encoding for you. URI url = new URI("http", "foo.com", "/hello world/", ""); And then convert the URI to a URL. URL url = uriz.toURL();

MALFORMED URL EXCEPTION


Each of the four URL constructors throws a MalformedURLException if the arguments to the constructor refer to a null or unknown protocol. try { URL myURL = new URL(. . .) } catch (MalformedURLException e) { ... // exception handler code here ..... }

PARSING A URL
The URL class provides several methods to query URL objects. getProtocol Returns the protocol identifier component of the URL. getAuthority Returns the authority component of the URL. getHost Returns the host name component of the URL. getPort Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1. getPath Returns the path component of this URL. getQuery Returns the query component of this URL. getFile Returns the filename component of the URL. The getFile method returns the same as getPath, plus the concatenation of the value of getQuery, if any. getRef Returns the reference component of the URL. Create a new URL object and call any of the accessor methods for the information.

READING DIRECTLY FROM A URL


After creating a URL call the URL's openStream() method to get a stream from which the contents of the URL is read. The openStream() method returns a java.io.InputStreamobject, so reading from a URL is as easy as reading from an input stream. The following small Java program uses openStream() to get an input stream on the URL http://www.yahoo.com/. It then opens a BufferedReader on the input stream and reads from the BufferedReader thereby reading from the URL. Everything read is copied to the standard output stream:

CONNECTING TO A URL
After creating a URL object call the URL object's openConnection method to get a URLConnection object, or one of its protocol specific subclasses, e.g. java.net.HttpURLConnection .

The URLConnection object setup parameters and general request properties that is needed before connecting. Connection to the remote object represented by the URL is only initiated when the URLConnection.connect method is called.

READING FROM AND WRITING TO A URLCONNECTION


The URLConnection class contains many methods that let you communicate with the URL over the network. URLConnection is an HTTP-centric class; that is, many of its methods are useful only when working with HTTP URLs. However, most URL protocols allows to read from and write to the connection. This section describes both functions.

READING FROM A URLCONNECTION


The following program performs the same function as the URLReader program shown in Reading Directly from a URL. However, rather than getting an input stream directly from the URL, this program explicitly retrieves a URLConnection object and gets an input stream from the connection. The connection is opened implicitly by calling getInputStream. Then, like URLReader, this program creates a BufferedReader on the input stream and reads from it.

WRITING TO A URLCONNECTION
Many HTML pages contain forms-- text fields and other GUI objects that enter data to send to the server. After typing the required information and initiate the query by clicking a button, theWeb browser writes the data to the URL over the network. At the other end the server receives the data, processes it, and then sends you a response, usually in the form of a new HTML page. Many of these HTML forms use the HTTP POST METHOD to send data to the server. Thus writing to a URL is often called posting to a URL. The server recognizes the POST request and reads the data sent from the client.

CREATE A URL
1. 2. 3. 4. 5. 6. Retrieve the URLConnection object. Set output capability on the URLConnection. Open a connection to the resource. Get an output stream from the connection. Write to the output stream. Close the output stream.

OPENING URLCONNECTIONS
A program that uses the URLConnection class directly follows this basic sequence of steps: Construct a URL object. Invoke the URL object's openConnection( ) method to retrieve a URLConnection object for that URL. Configure the URLConnection. Read the header fields. Get an input stream and read data. Get an output stream and write data. Close the connection.

ADVANTAGES
It can serve more than one client .

DISADVANTAGES
A web server (program) has defined load limits, because it can handle only a limited number of concurrent client connections (usually between 2 and 60,000, by default between 500 and 1,000) per IP address (and IP port) and it can serve only a certain maximum number of requests per second depending on:

Its own settings. The HTTP request type. Content origin (static or dynamic). The fact that the served content is or is not cached. The hardware and software limits of the OS where it is working.

When a web server is near to or over its limits, it becomes overloaded and thus unresponsive.

APPLICATION
Used for implementing Digital Libraries. Used in checking email. Used in Online banking.

RELATED TEXT BOOKS

1. Behrouz A. Forouzan, Data communication and Networking, Tata McGraw-Hill, 2004. 2. James F. Kurose and Keith W. Ross, Computer Networking: A Top-Down Approach Featuring the Internet, Pearson Education, 2003. 3. Larry L.Peterson and Peter S. Davie, Computer Networks, Harcourt Asia Pvt. Ltd., Second Edition. 4. Andrew S. Tanenbaum, Computer Networks, PHI, Fourth Edition, 2003. 5. William Stallings, Data and Computer Communication, Sixth Edition, Pearson Education, 2000.

RELATED WEB LINKS


1. 2. 3. 4. 5. 6. 7. 8. www.wikipedia.com www.google.com www.altavista.com www.java.sun.com www.programmersheaven.com RFC 1945 - Hypertext Transfer Protocol -- HTTP/1.0 (French translation) RFC 1945 - Hypertext Transfer Protocol -- HTTP/1.0 (original version) RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1 (original version)

EX.NO:6b DATE:
AIM

UNIFORM RESOURCE LOCATOR (URL)

To retrieve the data using Uniform Resource Locators

ALGORITHM
Step 1: Start the Program. Step 2: Create an object for the URL class. Step 3: Specify the address from which the data is to be retrieved inside the URL class Step 4: Open the URL connection Step 5: Request the content Length, modified date etc. using appropriate the methods. Step 6: Display the contents to the user Step 7: Stop the program

UNIFORM RESOURCE LOCATOR


#include<iostream.h> #include<stdio.h> #include<dos.h> #include<conio.h> #include<string.h> void main()

{ char c; int len=0; struct date d; struct time t; clrscr(); FILE *fp; getdate(&d); gettime(&t); fp=fopen("welcome.html","r"); printf("Content type = text/html\n"); printf("\n Date : %d-%d-%d Time : %d:%d:%d \n",d.da_day,d.da_mon,d.da_year,t.ti_hour,t.ti_min,t.ti_sec); c=fgetc(fp); cout<<c; len++; while((c=fgetc(fp))!=-1) { if(c!='\n'||' '); len++; cout<<c; } printf("\n Content length is %d",len); getch(); }

OUTPUT:
CONTENT TYPE=text/html Date:03-11-2010 time:15:13:28 <html>

<head> <title>welcome</title> <body bgcolor=blue> <h1>welcome to network lab-1</h> </body> </html> content length is 109

RESULT
Thus the program for retrieving the data using URL is executed and the output is verified successfully.

MULTI USER CHAT


CLIENT SERVER ARCHITECTURE:
In the client server architecture, a machine (refered as client) makes a request to connect to another machine (called as server) for providing some service. The services running on the server run on known ports (application identifiers) and the client needs to know the address of

the server machine and this port in order to connect to the server. On the other hand, the server does not need to know about the address or the port of the client at the time of connection initiation. The first packet which the client sends as a request to the server contains these information about the client which are further used by the server to send any information. Client acts as the active device which makes the first move to establish the connection whereas the server passively waits for such requests from some client.

ILLUSTRATION OF CLIENT SERVER MODEL


What is a Socket? In unix, whenever there is a need for inter process communication within the same machine, we use mechanism like signals or pipes (named or unnamed). Similarly, when we desire a communication between two applications possibly running on different machines, we need sockets. Sockets are treated as another entry in the unix open file table. So all the system calls which can be used for any IO in unix can be used on socket. The server and client applications use various system calls to connect which use the basic construct called socket. A socket is one end of the communication channel between two applications running on different machines. Steps followed by client to establish the connection: 1. Create a socket 2. Connect the socket to the address of the server 3. Send/Receive data 4. Close the socket Steps followed by server to establish the connection: 1. Create a socket 2. Bind the socket to the port number known to all clients 3. Listen for the connection request 4. Accept connection request 5. Send/Receive data

CLIENT-SERVER COMMUNICATION OVERVIEW:


The analogy given below is often very useful in understanding many such networking concepts. The analogy is of a number of people in a room communicating with each other by way of talking. In a typical scenario, if A has to talk to B, then he would call out the name of B and only if B was listening would he respond. In case B responds, then one can say that a connection has been established. Henceforth until both of them desire to communicate, they can carry out their conversation.

A Client-Server architecture generally employed in networks is also very similar in concept. Each machine can act as a client or a server. Server: It is normally defined which provides some services to the client programs. However, we will have a deeper look at the concept of a "service" in this respect later. The most important feature of a server is that it is a passive entry, one that listens for request from the clients. Client: It is the active entity of the architecture, one that generated this request to connect to a particular port number on a particular server Communication takes the form of the client process sending a message over the network to the server process. The client process then waits for a reply message. When the server process gets the request, it performs the requested work and sends back a reply. The server that the client will try to connect to should be up and running before the client can be executed. In most of the cases, the server runs continuously as a daemon. There is a general misconception that servers necessarily provide some service and is therefore called a server. For example an e-mail client provides as much service as an mail server does. Actually the term service is not very well defined. So it would be better not to refer to the term at all. In fact servers can be programmed to do practically anything that a normal application can do. In brief, a server is just an entity that listens/waits for requests. To send a request, the client needs to know the address of the server as well as the port number which has to be supplied to establish a connection. One option is to make the server choose a random number as a port number, which will be somehow conveyed to the client. Subsequently the client will use this port number to send requests. This method has severe limitations as such information has to be communicated offline, the network connection not yet being established. A better option would be to ensure that the server runs on the same port number always and the client already has knowledge as to which port provides which service. Such standardization already exists. The port numbers 0-1023 are reserved for the use of the super user only. The list of the services and the ports can be found in the file /etc/services.

Connection Oriented vs. Connectionless Communication


Connection Oriented Communication: Analogous to the telephone network. The sender requests for a communication (dial the number), the receiver gets an indication (the phone ring) the receiver accepts the connection (picks up the phone) and the sender receives the acknowledgment (the ring stops). The connection is established through a dedicated link provided for the communication. This type of communication is characterized by a high level of reliability in terms of the number and the sequence of bytes. Connectionless Communication: Analogous to the postal service. Packets (letters) are sent at a time to a particular destination. For greater reliability, the receiver may send an acknowledgement (a receipt for the registered letters). Based on this two types of communication, two kinds of sockets are used: Stream sockets: used for connection-oriented communication, when reliability in connection is desired.

Datagram sockets: used for connectionless communication, when reliability is not as much as an issue compared to the cost of providing that reliability. For eg. streaming audio/video is always send over such sockets so as to diminish network traffic.

Ex.No:8

MULTICLIENT-SERVER CHAT

Date:
AIM:
To write a C program for implementing Client-Server Chat using TCP.

ALGORITHM:
SERVER: Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as type. Step 3: Name the socket using bind ( ) system call with the parameters server_sockfd and the server address (sin_addr and sin_sport). Step 4: Create a connection queue and wait for clients using the listen( ) system call with the number of clients request as parameters. Step 5: Get the clients id as input from the user to communicate. If the clients id is 0 then go to step 10 otherwise go to step 6. Step 6: Accept the connection using accept ( ) system call when client requests for connection. Step 7: Get the message which has to be sent to the client and check that it is not equal to Bye. Step 8: If the message is not equal to Bye then write the message to the client and Goto step 6. Step 9: If the message is Bye then terminates the connection with current client and Go to step 5. Step 10: Stop the program execution. CLIENT: Step 1: Start the program. Step 2: Create an unnamed socket for client using socket ( ) system. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type. Step 4: Name the socket using bind( ) system call. Step 5: Now connect the socket to server using connect ( ) system call. Step 6: Read the message from the server socket and compare it with Bye. Step 7: If the message is not equal to Bye then print the message to the server output device and repeat the steps 6 & 7. Step 8: Get the message from the client side. Step 9: Write the message to server sockfd and goto step 4. Step 10: If the message is equal to Byethen print good bye message and terminate the process. Step 11: Stop the process.

MULTI USER CHAT

SERVER
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,sd2,nsd,clilen,sport,len; char sendmsg[20],rcvmsg[20]; struct sockaddr_in servaddr,cliaddr; printf(Enter the port no:\n); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf("Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); do { printf("Enter the client no to communicate\n"); scanf("%d",&i); if(i==0) exit(0); printf("Client %d is connected\n",i); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); do { recv(nsd,rcvmsg,20,0);

printf("%s",rcvmsg); fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(nsd,sendmsg,20,0); wait(20); }while(strcmp(sendmsg,"bye")!=0); }while(i!=0); }

CLIENT - 1
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],revmsg[20]; struct sockaddr_in servaddr; printf("Enter the port no:\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); do { fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(csd,sendmsg,20,0); wait(20); recv(csd,revmsg,20,0); printf("%s",revmsg);

} while(strcmp(revmsg,"bye")!=0); }

CLIENT - 2
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],revmsg[20]; struct sockaddr_in servaddr; printf("Enter the port no:\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); do { fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(csd,sendmsg,20,0); wait(20); recv(csd,revmsg,20,0); printf("%s",revmsg); } while(strcmp(revmsg,"bye")!=0); }

OUTPUT:

SERVER SIDE: [1me2@localhost ~]$ vi Multiuserserver.c [1me2@localhost ~]$ cc Multiuserserverc [1me2@localhost ~]$ ./a.out Enter the port no 8543 socket is created Binded Enter the client to communicate: 1 Client 1 is connected Accepted hiiiii Byeeeeee Enter the client no to communicate: 2 client 2 is connected Accepted hiiiiiiiiii hello Enter the client no to communicate: 0 CLIENT SIDE 1: [1me2@localhost ~]$ vi multiuserclient1.c [1me2@localhost ~]$ cc multiuserclient1.c [1me2@localhost ~]$ ./a.out Enter the port no 8543 Socket is created Connected hiiiiii Byeeeee

CLIENT SIDE 2:

[1me2@localhost ~]$ vi multiuserclient2.c [1me2@localhost ~]$ cc multiuserclient2.c [1me2@localhost ~]$ ./a.out Enter the port no 8543 Socket is created Connected Hiiiiiiiii hello

RESULT
Thus the C program for chat multiclient-serve chat program using tcp has been executed successfully.

Ex. No. 9

Network management Protocols

Simple Network Management Protocol (SNMP)


Simple Network Management Protocol (SNMP) is a UDP-based network protocol. It is used mostly in network management systems to monitor network-attached devices for conditions that warrant administrative attention. SNMP is a component of the Internet Protocol Suite as defined by the Internet Engineering Task Force (IETF). It consists of a set of standards for network management, including an application layer protocol, a database schema, and a set of data objects.[1] SNMP exposes management data in the form of variables on the managed systems (Slaves), which describe the system configuration. These variables can then be queried (and sometimes set) by managing applications (Masters).

Overview and basic concepts


In typical SNMP use, one or more administrative computers have the task of monitoring or managing a group of hosts or devices on a computer network. Each managed system (also called Slave) executes, at all times, a software component called an agent (see below) which reports information via SNMP to the managing systems (also called Masters). Essentially, SNMP agents expose management data on the managed systems (Slaves) as variables (such as "free memory", "system name", "number of running processes", "default route"). But the protocol also permits active management tasks, such as modifying and applying a new configuration. The managing system (Master) can retrieve the information through the GET, GETNEXT and GETBULK protocol operations or the agent (which is on Slave) will send data without being asked using TRAP or INFORM protocol operations. SNMPv3 INFORM messages are valuable because they provide a reliable way for this data to be acknowledged by the management system, which is important because SNMP is a UDP-based protocol. Management systems can also send configuration updates or controlling requests through the SET protocol operation to actively manage a system. Configuration and control operations are used only when changes are needed to the network infrastructure. The monitoring operations are usually performed on a regular basis. The variables accessible via SNMP are organized in hierarchies. These hierarchies, and other metadata (such as type and description of the variable), are described by Management Information Bases (MIBs). The SNMP protocol operates in the Application Layer of the Internet Protocol Suite (Layer 7 of the OSI model). Typically, SNMP uses UDP ports 161 for the agent and 162 for the manager. The manager may send requests from any available source port to port 161 in the agent (destination port). The agent response will be sent back to the source port. The manager typically receives notifications (TRAPs and INFORMs) on port 162. The agent may generate notifications from any available port.

SNMP Architecture Basic components


An SNMP-managed network consists of three key components: Managed device = Slave device Agent = software which runs on Slave device Network management system (NMS) = software which runs on Master A managed device is a network node that implements an SNMP interface that allows unidirectional (read-only) or bidirectional access to node-specific information. Managed devices exchange node-specific information with the NMSs. Sometimes called network elements, the managed devices can be any type of device, including, but not limited to, routers, access servers, switches, bridges, hubs, IP telephones, computer hosts, and printers. An agent is a network-management software module that resides on a managed device. An agent has local knowledge of management information and translates that information to or from an SNMP specific form. A network management system (NMS) executes applications that monitor and control managed devices. NMSs provide the bulk of the processing and memory resources required for network management. One or more NMSs may exist on any managed network.

The Internet management model


SNMP is part of the Internet network management architecture. This architecture is based on the interaction of many entities, as described in the following section. As specified in Internet RFCs and other documents a network management system comprises:

Network elementsSometimes called managed devices, network elements are hardware devices such as computers, routers, and terminal servers that are connected to networks. AgentsAgents are software modules that reside in network elements. They collect and store management information such as the number of error packets received by a network element.

Managed objectA managed object is a characteristic of something that can be managed. For example, a list of currently active TCP circuits in a particular host computer is a managed object. Managed objects differ from variables, which are particular object instances. Using our example, an object instance is a single active TCP circuit in a particular host computer. Managed objects can be scalar (defining a single object instance) or tabular (defining multiple, related instances). Management information base (MIB) -- A MIB is a collection of managed objects residing in a virtual information store. Collections of related managed objects are defined in specific MIB modules. Syntax notationA syntax notation is a language used to describe a MIB's managed objects in a machine-independent format. Consistent use of a syntax notation allows different types of computers to share information. Internet management systems use a subset of the International Organization for Standardization's (ISO's) Open System Interconnection (OSI) Abstract Syntax Notation (ASN.1) to define both the packets exchanged by the management protocol and the objects that are to be managed. Structure of Management Information (SMI) -- The SMI defines the rules for describing management information. The SMI is defined using ASN.1. Network management stations (NMSs) -- Sometimes called consoles, these devices execute management applications that monitor and control network elements. Physically, NMSs are usually engineering workstation-caliber computers with fast CPUs, megapixel color displays, substantial memory, and abundant disk space. At least one NMS must be present in each managed environment. PartiesNewly defined in SNMPv2, a party is a logical SNMPv2 entity that can initiate or receive SNMPv2 communication. Each SNMPv2 party comprises a single, unique party identity, a logical network location, a single authentication protocol, and a single privacy protocol. SNMPv2 messages are communicated between two parties. An SNMPv2 entity can define multiple parties, each with different parameters. For example, different parties can use different authentication and/or privacy protocols. Management protocolA management protocol is used to convey management information between agents and NMSs. SNMP is the Internet community's de facto standard management protocol.

Management Information Base


SNMP itself does not define which information (which variables) a managed system should offer. Rather, SNMP uses an extensible design, where the available information is defined by management information bases (MIBs). MIBs describe the structure of the management data of a device subsystem; they use a hierarchical namespace containing object identifiers (OID). Each OID identifies a variable that can be read or set via SNMP. MIBs use the notation defined by ASN.1. The MIB hierarchy can be depicted as a tree with a nameless root, the levels of which are assigned by different organizations. The top-level MIB OIDs belong to different standards organizations, while lower-level object IDs are allocated by associated organizations. This model permits management across all layers of the OSI reference model, extending into applications such as databases, email, and the Java reference model, as MIBs can be defined for all such area-specific information and operations.

A managed object (sometimes called a MIB object, an object, or a MIB) is one of any number of specific characteristics of a managed device. Managed objects are made up of one or more object instances (identified by their OIDs), which are essentially variables. Two types of managed objects exist: o Scalar objects define a single object instance. o Tabular objects define multiple related object instances that are grouped in MIB tables. An example of a managed object is atInput, which is a scalar object that contains a single object instance, the integer value that indicates the total number of input AppleTalk packets on a router interface. An object identifier (or object ID or OID) uniquely identifies a managed object in the MIB hierarchy.

Advantages
Its simple design makes it easy to implement Not too stressful on an existing network SNMP is widely used Easy to update Easily Expandable to meet increased needs

Disadvantages

Poor security that allows unauthorized users to access management agents or intercept commands1 Since UDP exchanges are unacknowledged, the management agent receives no confirmation that communications have successfully reached the management console Too simple provides information that is not detailed or organized enough3 Generates a lot of network traffic as it polls devices for status information

Applications
SNMP can be helpful for managing large networks, and some router manufacturers are including SNMP functions in their routers, most notably Linksys. Need to use some sort of SNMP utility to capture and read the generated messages, however. Linux and Unix users won't have much of a problem finding SNMP Trap utilities, but Windows and MacOS users may need more help.

References
1. RFC 3411 An Architecture for Describing Simple Network Management Protocol (SNMP) Management Frameworks 2. SNMP Version 3 links hub 3. RFC Editor List of current Internet Standards (STDs) 4. RFC Editor List of HISTORIC RFCs 5. In This Issue: SNMP Version 3 The Simple Times ISSN 1060-6080 6. SNMPv3 Cisco 7. SNMP Research presentations in favor of standards-based management over proprietary CLIs

Ex. No:9 Date:


AIM:

SIMULATION OF SIMPLE NETWORK MANAGEMENT PROTOCOLS

To write a C program for simulation of Simple Network management Protocols.

ALGORITHM:
MANAGER: Step 1: Start the program. Step 2: Create an unnamed socket for client using socket ( ) system. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type. Step 4: Name the socket using bind ( ) system call. Step 5: Now connect the socket to agent using connect ( ) system call. Step 6: Get the input for the type of information needed from the agent. Step 7: If the input is equal to TCP connection then goto next step else If it is equal to system Goto step 9. Step 8: Read the input for the object, send it and receive the details of the TCP connection of that object from the agent. Go to step 10. Step 9: Read the input for the object, send it and receive the details of the system from the agent. Go to step 10. Step 10: Receive the message, print and terminate the process. Step 11: Stop the process.

AGENTS
Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as type. Step 3: Name the socket using bind( ) system call with the parameters server_sockfd and the manager address(sin_addr and sin_sport). Step 4: Create a connection queue and wait for manager using the listen ( ) system call with the number of manager request as parameters. Step 5: Accept the connection using accept( ) system call when manager requests for connection. Step 6: Receive the message from the manager. If the request is for TCP connections then send the details of the requested object, else if the request is for System then send the details of the requested system. Step 7: Stop the program execution.

SIMPLE NETWORK MANAGEMENT PROTOCOL


AGENT1 #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,sd2,nsd,clilen,sport,len; char sendmsg[20],recvmsg[100]; char oid[5][10]={"client1","client2","client3","cleint4","client5"}; char wsize[5][5]={"5","10","15","3","6"}; struct sockaddr_in servaddr,cliaddr; printf("I'm the Agent - TCP Connection\n"); printf("\nEnter the Server port"); printf("\n_____________________\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf(" Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); recv(nsd,recvmsg,100,0); for (i=0;i<5;i++) {

if(strcmp(recvmsg,oid[i])==0) { send(nsd,wsize[i],100,0); break; } } } AGENT 2 #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,sd2,nsd,clilen,sport,len; char sendmsg[20],recvmsg[100]; char oid[5][10]={"System1","System2","System3","System4","System5"}; char mdate[5][15]={"1-10-095","10-03-08","14.03.81","11.07.07","17.12.77"}; char time[5][15]={"9am","10pm","11am","12.30pm","11.30am"}; struct sockaddr_in servaddr,cliaddr; printf("Enter the Server port"); printf("\n_____________________\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf(" Can't Bind\n"); else printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen);

if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); recv(nsd,recvmsg,100,0); for(i=0;i<5;i++) { if(strcmp(recvmsg,oid[i])==0) { send(nsd,mdate[i],100,0); send(nsd,time[i],100,0); break; } } }

MANAGER
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len,i; char sendmsg[20],rcvmsg[100],rmsg[100],oid[100]; struct sockaddr_in servaddr; printf("Enter the port\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Scocket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n");

printf("\n 1.TCP Connection\n"); printf("\n 2. System \n"); printf("Enter the number for the type of informtion needed....\n"); scanf("%d",&i); if(i==1) { printf("Enter the Object ID for Client\n"); scanf("%s",oid); send(csd,oid,100,0); recv(csd,rmsg,100,0); printf("\n The window size of %s is %s",oid,rmsg); } else { printf("\nEnter the Object ID for the System\n"); scanf("%s",oid); send(csd,oid,100,0); recv(csd,rmsg,100,0); printf("\nThe Manufacturing date for %s is %s",oid,rmsg); recv(csd,rmsg,100,0); printf("\nThe time of Last Utilization for %s is %s",oid,rmsg); } }

OUTPUT:
AGENT1: [1me14@localhost ~]$ vi Agent1.c [1me14@localhost ~]$ cc Agent1.c [1me14@localhost ~]$ ./a.out I'm the Agent - TCP Connection Enter the Server port _____________________ 8543 Socket is created Binded Accepted MANGER: [1me14@localhost ~]$ vi Manager.c [1me14@localhost ~]$ cc Manger.c [1me14@localhost ~]$ ./a.out Enter the port 8543 Socket is Created Connected 1.TCP Connection 2. System Enter the number for the type of information needed: 1 Enter the Object ID for Client: Client1 The window size of client1 is 5 AGENT2: [1me14@localhost ~]$ vi Agent2.c [1me14@localhost ~]$ cc Agent2.c [1me14@localhost ~]$ ./a.out Enter the Server port _____________________ 8543 Socket is Created Binded Accepted

MANGER: [1me14@localhost ~]$ vi Manager.c [1me14@localhost ~]$ cc Manger.c [1me14@localhost ~]$ ./a.out Enter the port 8543 Socket is Created Connected 1.TCP Connection 2. System Enter the number for the type of informtion needed: 2 Enter the Object ID for Client: System3 The Manufacturing date for system3 is 14.03.81 The time of last utilization for system3 is 11am

RESULT
Thus the C program for simple network management protocols has been executed successfully.

ELECTRONIC MAIL
E-MAIL:
Electronic mail, often abbreviated as email, e.mail or e-mail, is a method of exchanging digital messages, designed primarily for human use. E-mail systems are based on a store-andforward model in which e-mail computer server systems accept, forward, deliver and store messages on behalf of users, who only need to connect to the e-mail infrastructure, typically an e-mail server, with a network-enabled device (e.g., a personal computer) for the duration of message submission or retrieval. Originally, e-mail was always transmitted directly from one user's device to another's; nowadays this is rarely the case. An electronic mail message consists of two components, the message header, and the message body, which is the email's content. The message header contains control information, including, minimally, an originator's email address and one or more recipient addresses. Usually additional information is added, such as a subject header field. Originally a text-only communications medium, email was extended to carry multi-media content attachments, which were standardized in with RFC 2045 through RFC 2049, collectively called, Multipurpose Internet Mail Extensions (MIME). The foundation for today's global Internet e-mail service was created in the early ARPANET and standards for encoding of messages were proposed as early as, for example, in 1973 (RFC 561). An e-mail sent in the early 1970s looked very similar to one sent on the Internet today. Conversion from the ARPANET to the Internet in the early 1980s produced the core of the current service. Network-based email was initially exchanged on the ARPANET in extensions to the File Transfer Protocol (FTP), but is today carried by the Simple Mail Transfer Protocol (SMTP), first published as Internet standard 10 (RFC 821) in 1982. In the process of transporting email messages between systems, SMTP communicates delivery parameters using a message envelope separately from the message (headers and body) itself.

ORIGIN:
Electronic mail predates the inception of the Internet, and was in fact a crucial tool in creating the Internet. MIT first demonstrated the Compatible Time-Sharing System (CTSS) in 1961.[16] It allowed multiple users to log into the IBM 7094[17] from remote dial-up terminals, and to store files online on disk. This new ability encouraged users to share information in new ways. E-mail started in 1965 as a way for multiple users of a time-sharing mainframe computer to

communicate. Although the exact history is murky, among the first systems to have such a facility were SDC's Q32 and MIT's CTSS.

HOST-BASED MAILSYSTEMS:
The original email systems allowed communication only between users who logged into the one host or "mainframe", but this could be hundreds or thousands of users within a company or university. By 1966 (or earlier, it is possible that the SAGE system had something similar some time before), such systems allowed email between different companies as long as they ran compatible operating systems, but not to other dissimilar systems. Examples include BITNET, IBM PROFS, Digital All-in-1 and the original Unix mail.

LAN-BASED MAILSYSTEMS:
From the early 1980s networked personal computers on LANs became increasingly important - and server-based systems similar to the earlier mainframe systems developed, and again initially allowed communication only between users logged into the one server, but these also could generally be linked between different companies as long as they ran the same email system and (proprietary) protocol. Examples include cc:Mail, WordPerfect Office, Microsoft Mail, Banyan VINES and Lotus Notes - with various vendors supplying gateway software to link these incompatible systems.

MESSAGE FORMAT:
The Internet e-mail message format is defined in RFC 5322 and a series of RFCs, RFC 2045 through RFC 2049, collectively called, Multipurpose Internet Mail Extensions, or MIME. Although as of July 13, 2005, RFC 2822 is technically a proposed IETF standard and the MIME RFCs are draft IETF standards,[22] these documents are the standards for the format of Internet email. Prior to the introduction of RFC 2822 in 2001, the format described by RFC 822 was the standard for Internet e-mail for nearly 20 years; it is still the official IETF standard. The IETF reserved the numbers 5321 and 5322 for the updated versions of RFC 2821 (SMTP) and RFC 2822, as it previously did with RFC 821 and RFC 822, honoring the extreme importance of these two RFCs. RFC 822 was published in 1982 and based on the earlier RFC 733 (see[23]).

Internet e-mail messages consist of two major sections:


Header Structured into fields such as summary, sender, receiver, and other information about the e-mail. Body The message itself as unstructured text; sometimes containing a signature block at the end. This is exactly the same as the body of a regular letter.

The header is separated from the body by a blank line.

MESSAGE HEADER:
Each message has exactly one header, which is structured into fields. Each field has a name and a value. RFC 5322 specifies the precise syntax. Informally, each line of text in the header that begins with a printable character begins a separate field. The field name starts in the first character of the line and ends before the separator character ":". The separator is then followed by the field value (the "body" of the field). The value is continued onto subsequent lines if those lines have a space or tab as their first character. Field names and values are restricted to 7-bit ASCII characters. Non-ASCII values may be represented using MIME encoded words.

HEADER FIELDS
The message header should include at least the following fields:

From: The e-mail address, and optionally the name of the author(s). In many e-mail clients not changeable except through changing account settings. To: The e-mail address(es), and optionally name(s) of the message's recipient(s). Indicates primary recipients (multiple allowed), for secondary recipients see Cc: and Bcc: below. Subject: A brief summary of the topic of the message. Date: The local time and date when the message was written. Like the From: field, many email clients fill this in automatically when sending. The recipient's client may then display the time in the format and time zone local to her. Message-ID: Also an automatically generated field; used to prevent multiple delivery and for reference in In-Reply-To: (see below).

Note that the "To:" field is not necessarily related to the addresses to which the message is delivered. The actual delivery list is supplied separately to the transport protocol, SMTP, which may or may not originally have been extracted from the header content. The "To:" field is similar to the addressing at the top of a conventional letter which is delivered according to the address on the outer envelope. Also note that the "From:" field does not have to be the real sender of the e-mail message. One reason is that it is very easy to fake the "From:" field and let a message seem to be from any mail address. It is possible to digitally sign e-mail, which is much harder to

fake, but such signatures require extra programming and often external programs to verify. Some Internet service providers do not relay e-mail claiming to come from a domain not hosted by them, but very few (if any) check to make sure that the person or even e-mail address named in the "From:" field is the one associated with the connection. Some Internet service providers apply e-mail authentication systems to e-mail being sent through their MTA to allow other MTAs to detect forged spam that might appear to come from them. RFC 3864 describes registration procedures for message header fields at the IANA; it provides for permanent and provisional message header field names, including also fields defined for MIME, netnews, and http, and referencing relevant RFCs. Common header fields for email include:

Bcc: Blind Carbon Copy; addresses added to the SMTP delivery list but not (usually) listed in the message data, remaining invisible to other recipients. Cc: Carbon copy; Many e-mail clients will mark e-mail in your inbox differently depending on whether you are in the To: or Cc: list. Content-Type: Information about how the message is to be displayed, usually a MIME type. In-Reply-To: Message-ID of the message that this is a reply to. Used to link related messages together. Precedence: commonly with values "bulk", "junk", or "list"; used to indicate that automated "vacation" or "out of office" responses should not be returned for this mail, eg. to prevent vacation notices from being sent to all other subscribers of a mailinglist. Received: Tracking information generated by mail servers that have previously handled a message, in reverse order (last handler first). References: Message-ID of the message that this is a reply to, and the message-id of the message the previous was reply a reply to, etc. Reply-To: Address that should be used to reply to the message. Sender: Address of the actual sender acting on behalf of the author listed in the From: field (secretary, list manager, etc.). X-Face: Small icon.

SERVERS AND CLIENT APPLICATIONS:


The interface of an e-mail client, Thunderbird. Messages are exchanged between hosts using the Simple Mail Transfer Protocol with software programs called mail transfer agents. Users can retrieve their messages from servers using standard protocols such as POP or IMAP, or, as is more likely in a large corporate environment, with a proprietary protocol specific to Lotus Notes or Microsoft Exchange Servers. Webmail interfaces allow users to access their mail with any standard web browser, from any computer, rather than relying on an e-mail client.

Mail can be stored on the client, on the server side, or in both places. Standard formats for mailboxes include Maildir and mbox. Several prominent e-mail clients use their own proprietary format and require conversion software to transfer e-mail between them. Accepting a message obliges an MTA to deliver it, and when a message cannot be delivered, that MTA must send a bounce message back to the sender, indicating the problem.

FILENAME EXTENSIONS:
Upon reception of e-mail messages, e-mail client applications save message in operating system files in the filesystem. Some clients save individual messages as separate files, while others use various database formats, often proprietary, for collective storage. A historical standard of storage is the mbox format. The specific format used is often indicated by special filename extensions:
.eml

Used by many e-mail clients including Microsoft Outlook Express, Windows Mail and Mozilla Thunderbird.[30] The files are plain text in MIME format, containing the e-mail header as well as the message contents and attachments in one or more of several formats.
.emlx .msg .mbx

Used by Apple Mail. Used by Microsoft Office Outlook. Used by Opera Mail, KMail, and Apple Mail based on the mbox format.

Some applications (like Apple Mail) also encode attachments into messages for searching while also producing a physical copy of the files on a disk. Others separate attachments from messages by depositing them into designated folders on disk.

ADVANTAGES:

The problem of logistics

E-mail provides a way to exchange information between two or more people with no set-up costs and that is generally far less expensive than physical meetings or phone calls.

The problem of synchronization

E-mail allows asynchrony: each participant may control their schedule independently.

DISADVANTAGES:

Loss of Context: which means that the context is lost forever; there is no way to get the text back.

Information in context (as in a newspaper) is much easier and faster to understand than unedited and sometimes unrelated fragments of information. Communicating in context can only be achieved when both parties have a full understanding of the context and issue in question.

Information overload:

E-mail is a push technologythe sender controls who receives the information. Convenient availability of mailing lists and use of "copy all" can lead to people receiving unwanted or irrelevant information of no use to them.

Inconsistency:

E-mail can duplicate information. This can be a problem when a large team is working on documents and information while not in constant contact with the other members of their team.

APPLICATIONS
In society
Research has shown that people actively use e-mail to maintain core social networks, particularly when others live at a distanceWith the introduction of chat messengers and

video conference there are more ways to communicate. Flaming


Flaming occurs when a person sends a message with angry or antagonistic content. Flaming is assumed to be more common today because of the ease and impersonality of email communications: confrontations in person or via telephone require direct interaction, where social norms encourage civility, whereas typing a message to another person is an indirect interaction, so civility may be forgotten.

E-mail bankruptcy
Also known as "e-mail fatigue", e-mail bankruptcy is when a user ignores a large number of e-mail messages after falling behind in reading and answering them. The reason

for falling behind is often due to information overload and a general sense there is so much information that it is not possible to read it all. As a solution, people occasionally send a boilerplate message explaining that the e-mail inbox is being cleared out.

In business
E-mail was widely accepted by the business community as the first broad electronic communication medium and was the first e-revolution in business communication. E-mail is very simple to understand and like postal mail, e-mail solves two basic problems of communication: logistics and synchronization (see below).

REFERENCES
1. ^ "A Matter of (Wired News) Style", Tony Long, Wired magazine, 23 October 2000 2. ^ "Readers on (Wired News) Style", Wired magazine, 24 October 2000 3. ^ "RFC Editor Terms List". IETF. http://www.rfc-editor.org/rfc-style-guide/termsonline-03.txt. 4. ^ AskOxford Language Query team. "What is the correct way to spell 'e' words such as 'email', 'ecommerce', 'egovernment'?". FAQ. Oxford University Press. http://www.askoxford.com/asktheexperts/faq/aboutspelling/email. Retrieved 4 September 2009. "We recommend email, as this is now by far the most common form" 5. ^ Reference.com 6. ^ Random House Unabridged Dictionary, 2006

Ex.No: Date:

ELECTRONIC MAIL

AIM:
To email the contents of a file.

ALGORITHM:
Step 1: Start the Program Step 2: Get the input from the user for the file to mail to the list of mailids. Step 3: The file size is compared with the mailids size. If the file size is greater than mailids size then display the error, otherwise go to step 4. Step 4: The contents of a file are transferred using mail statement followed by the Subject. Step 5: The user can open the Inbox to see the incoming messages by specifying mail userid Step 6: Stop the program

EMAIL
#include <stdlib.h> #include <string.h> #define cknull(x) if((x)==NULL) {perror(""); exit(EXIT_FAILURE);} #define cknltz(x) if((x)<0) {perror(""); exit(EXIT_FAILURE);} #define LIST_LEN 4 //char *f="sam.txt"; void email_it(char *filename); main() { char fname[15]; printf("enter the filename\n"); scanf("%s",fname); email_it(fname); } void email_it(char *filename) { char tmp[256]={0x0}; char fpBuffer[400]={0x0}; char email_list[LIST_LEN][256]={{"mecse3@localhost.localdomain"},{0x0}}; int i=0; for(i=0;*email_list[i]>0x0;i++) { cknull(strcpy(tmp, email_list[i])); cknltz(sprintf (fpBuffer,"mail -s '%s %s' %s < %s", "Please Review:", filename, tmp,filename)); if(system (fpBuffer)==(-1)) { perror("email failure"); exit(EXIT_FAILURE); } } }

OUTPUT:
[1me2@localhost ~]$ vi email.c [1me2@localhost ~]$ cc email.c [1me2@localhost ~]$ ./a.out Enter the file name: sample.c [1me2@localhost ~]$/home/1me1/dead.letter.saved message in /home/1me1/dead.letter..

RESULT
Thus the program for developing E-mail application is executed and the output is verified successfully.

STUDY OF NETWORK SIMULATOR PACKAGES


Ex. No: Date:
AIM:
To study about NS2 - Network Simulator

STUDY OF NS2

INTRODUCTION:
NS is a discrete event simulator targeted at networking research. NS provides substantial support for simulation of TCP, routing, and multicast protocols over wired and wireless (local and satellite) networks. NS began as a variant of the REAL network simulator in 1989 and has evolved substantially over the past few years. In 1995 ns development was supported by DARPA through the VINT project at LBL, Xerox PARC, UCB, and USC/ISI. Currently ns development is support through DARPA with SAMAN and through NSF with CONSER, both in collaboration with other researchers including ACIRI. NS has always included substantial contributions from other researchers, including wireless code from the UCB Daedelus and CMU Monarch projects and Sun Microsystems. The network simulator ns-2 is a widely accepted discrete event network simulator, actively used for wired and wireless network simulations. It has a highly detailed model of the lower layers (Physical and MAC) of wireless IEEE 802.11 networks. Ns-2 has also an emulation feature, i.e. the ability to introduce the simulator into a live network and to simulate a desired network between real applications in real-time. Within the scope of this project we developed some methods and extensions to the ns-2 to combine wireless network simulation and network emulation.

OVERVIEW:
NS is an event driven network simulator developed at UC Berkeley that simulates variety of IP networks. It implements network protocols such as TCP and UDP, traffic source behavior such as FTP, Telnet, Web, CBR and VBR, router queue management mechanism such as Drop Tail, RED and CBQ, routing algorithms such as Dijkstra, and more. NS also implements multicasting and some of the MAC layer protocols for LAN simulations. The NS project is now a part of the VINT project that develops tools for simulation results display, analysis and converters that convert network topologies generated by well-known generators to NS formats. Currently, NS (version 2) written in C++ and OTcl (Tcl script language with Object-oriented extensions developed at MIT) is available. This document talks briefly about the basic structure of NS, and explains in detail how to use NS mostly by giving examples. Most of the figures that are used in describing the NS basic structure and network components are from the 5th VINT/NS Simulator Tutorial/Workshop slides and the NS Manual (formerly called "NS Notes and Documentation"), modified little bit as needed.

Figure 1. Simplified User's View of NS As shown in Figure 1, in a simplified user's view, NS is Object-oriented Tcl (OTcl) script interpreter that has a simulation event scheduler and network component object libraries, and network setup (plumbing) module libraries (actually, plumbing modules are implemented as member functions of the base simulator object). In other words, to use NS, you program in OTcl script language. To setup and run a simulation network, a user should write an OTcl script that initiates an event scheduler, sets up the network topology using the network objects and the plumbing functions in the library, and tells traffic sources when to start and stop transmitting packets through the event scheduler. The term "plumbing" is used for a network setup, because setting up a network is plumbing possible data paths among network objects by setting the "neighbor" pointer of an object to the address of an appropriate object. When a user wants to make a new network object, he or she can easily make an object either by writing a new object or by making a compound object from the object library, and plumb the data path through the object. This may sound like complicated job, but the plumbing OTcl modules actually make the job very easy. The power of NS comes from this plumbing. Another major component of NS beside network objects is the event scheduler. An event in NS is a packet ID that is unique for a packet with scheduled time and the pointer to an object that handles the event. In NS, an event scheduler keeps track of simulation time and fires all the events in the event queue scheduled for the current time by invoking appropriate network components, which usually are the ones who issued the events, and let them do the appropriate action associated with packet pointed by the event. Network components communicate with one another passing packets, however this does not consume actual simulation time. All the network components that need to spend some simulation time handling a packet (i.e. need a delay) use the event scheduler by issuing an event for the packet and waiting for the event to be fired to itself before doing further action handling the packet. For example, a network switch component that simulates a switch with 20 microseconds of switching delay issues an event for a packet to be switched to the scheduler as an event 20 microsecond later. The scheduler after 20 microseconds dequeues the event and fires it to the switch component, which then passes the packet to an appropriate output link component. Another use of an event scheduler is timer. NS is written not only in OTcl but in C++ also. For efficiency reason, NS separates the data path implementation from control path implementations. In order to reduce packet and event processing time (not simulation time), the event scheduler and the basic network component objects in the data path are written and compiled using C++. These compiled objects are made available to the OTcl interpreter through an OTcl linkage that creates a matching OTcl object for

each of the C++ objects and makes the control functions and the configurable variables specified by the C++ object act as member functions and member variables of the corresponding OTcl object. In this way, the controls of the C++ objects are given to OTcl. It is also possible to add member functions and variables to a C++ linked OTcl object. The objects in C++ that do not need to be controlled in a simulation or internally used by another object do not need to be linked to OTcl. Likewise, an object (not in the data path) can be entirely implemented in OTcl. Figure 2 shows an object hierarchy example in C++ and OTcl. One thing to note in the figure is that for C++ objects that have an OTcl linkage forming a hierarchy, there is a matching OTcl object hierarchy very similar to that of C++.

Figure 2. C++ and OTcl: The Duality

Figure 3. Architectural View of NS Figure 3 shows the general architecture of NS. In this figure a general user (not an NS developer) can be thought of standing at the left bottom corner, designing and running simulations in Tcl using the simulator objects in the OTcl library. The event schedulers and most of the network components are implemented in C++ and available to OTcl through an OTcl linkage that is implemented using tclcl. The whole thing together makes NS, which is a OO extended Tcl interpreter with network simulator libraries. This section briefly examined the general structure and architecture of NS. At this point, one might be wondering about how to obtain NS simulation results. As shown in Figure 1, when a simulation is finished, NS produces one or more text-based output files that contain detailed simulation data, if specified to do so in the input Tcl (or more specifically, OTcl) script. The data can be used for simulation analysis (two simulation result analysis examples are presented in later sections) or as an input to a graphical simulation display tool called Network Animator (NAM) that is developed as a part of VINT project. NAM has a

nice graphical user interface similar to that of a CD player (play, fast forward, rewind, pause and so on), and also has a display speed controller. Furthermore, it can graphically present information such as throughput and number of packet drops at each link, although the graphical information cannot be used for accurate simulation analysis. This section shows a simple NS simulation script and explains what each line does. Example 3 is an OTcl script that creates the simple network configuration and runs the simulation scenario in Figure 4.

Figure 4. A Simple Network Topology and Simulation Scenario This network consists of 4 nodes (n0, n1, n2, n3) as shown in above figure. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each node uses a DropTail queue, of which the maximum size is 10. A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent attached to n3. As default, the maximum size of a packet that a "tcp" agent can generate is 1KByte. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and frees the received packets. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3. A "null" agent just frees the packets received. Example 3. A Simple NS Simulation Script The following is the explanation of the script above. In general, an NS script starts with making a Simulator object instance. set ns [new Simulator]: generates an NS simulator object instance, and assigns it to variable ns (italics is used for variables and values in this section). o Initialize the packet format (ignore this for now)

o Create a scheduler (default is calendar scheduler) o Select the default address format (ignore this for now) The "Simulator" object has member functions that do the following: Create compound objects such as nodes and links (described later) Connect network component objects created (ex. attach-agent) Set network component parameters (mostly for compound objects) Create connections between agents (ex. make connection between a "tcp" and "sink") Specify NAM display options Most of member functions are for simulation setup and scheduling, however some of them are for the NAM display. The "Simulator" object member function implementations are located in the "ns-2/tcl/lib/ns-lib.tcl" file. $ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). This member function of "Simulator" object is for the NAM display, and has no effect on the actual simulation. $ns namtrace-all file-descriptor: This member function tells the simulator to record simulation traces in NAM input format. It also gives the file name that the trace will be written to later by the command $ns flush-trace. Similarly, the member function trace-all is for recording the simulation trace in a general format. proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish". In this function, post-simulation processes are specified. set n0 [$ns node]: The member function node creates a node. A node in NS is compound object made of address and port classifiers (described in a later section). Users can create a node by separately creating an address and a port classifier objects and connecting them together. However, this member function of Simulator object makes the job easier. To see how a node is created, look at the files: "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/nsnode.tcl". $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of specified bandwidth and delay, and connects the two specified nodes. In NS, the output queue of a node is implemented as a part of a link, therefore users should specify the queue-type when creating links. In the above simulation script, DropTail queue is used. If the reader wants to use a RED queue, simply replace the word DropTail with RED. The NS implementation of a link is shown in a later section. Like a node, a link is a compound object, and users can create its sub-objects and connect them and the nodes. Link source codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl" files. One thing to note is that you can insert error modules in a link component to

simulate a lossy link (actually users can make and insert any network objects). Refer to the NS documentation to find out how to do this. $ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links that connect node1 and node2 to the number specified. At this point, the authors do not know how many of these kinds of member functions of Simulator objects are available and what they are. Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns2/tcl/libs/ns-link.tcl", or NS documentation for more information. $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM display. To see the effects of these lines, users can comment these lines out and try the simulation.

Now that the basic network setup is done, the next thing to do is to setup traffic agents such as TCP and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agents respectively. set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users can create any agent or traffic sources in this way. Agents and traffic sources are in fact basic objects (not compound objects), mostly implemented in C++ and linked to OTcl. Therefore, there are no specific Simulator object member functions that create these object instances. To create agents or traffic sources, a user should know the class names these objects (Agent/TCP, Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS documentation or partly in this documentation. But one shortcut is to look at the "ns-2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value settings for available network objects. Therefore, it works as a good indicator of what kind of network objects are available in NS and what are the configurable parameters. $ns attach-agent node agent: The attach-agent member function attaches an agent object created to a node object. Actually, what this function does is call the attach member function of specified node, which attaches the given agent to itself. Therefore, a user can do the same thing by, for example, $n0 attach $tcp. $ns connect agent1 agent2: After two agents that will communicate with each other are created, the next thing is to establish a logical network connection between them. This line establishes a network connection by setting the destination address to each others' network and port address pair.

Assuming that all the network configuration is done, the next thing to do is write a simulation scenario (i.e. simulation scheduling). The Simulator object has many scheduling member functions. However, the one that is mostly used is the following: $ns at time "string": This member function of a Simulator object makes the scheduler (scheduler_ is the variable that points the scheduler object created by [new Scheduler] command at the beginning of the script) to schedule the execution of the specified string at given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler call a start member function of the CBR traffic source object, which starts the CBR to transmit data. In NS, usually a traffic source does not transmit actual data, but it notifies

the underlying agent that it has some amount of data to transmit, and the agent, just knowing how much of the data to transfer, creates packets and sends them. After all network configuration, scheduling and post-simulation procedure specifications are done, the only thing left is to run the simulation. This is done by $ns run.

NETWORK COMPONENTS:

Figure 6. Class Hierarchy (Partial) The root of the hierarchy is the TclObject class that is the superclass of all OTcl library objects (scheduler, network components, timers and the other objects including NAM related ones). As an ancestor class of TclObject, NsObject class is the superclass of all basic network component objects that handle packets, which may compose compound network objects such as nodes and links. The basic network components are further divided into two subclasses, Connector and Classifier, based on the number of the possible output data paths. The basic network objects that have only one output data path are under the Connector class, and switching objects that have possible multiple output data paths are under the Classifier class.

NODE AND ROUTING:


A node is a compound object composed of a node entry object and classifiers as shown in Figure 7. There are two types of nodes in NS. A unicast node has an address classifier that does unicast routing and a port classifier. A multicast node, in addition, has a classifier that classify multicast packets from unicast packets and a multicast classifier that performs multicast routing.

Figure 7. Node (Unicast and Multicast) In NS, Unicast nodes are the default nodes. To create Multicast nodes the user must explicitly notify in the input OTcl script, right after creating a scheduler object, that all the nodes that will be created are multicast nodes. After specifying the node type, the user can also select a specific routing protocol other than using a default one. Unicast - $ns rtproto type - type: Static, Session, DV, cost, multi-path Multicast

- $ns multicast (right after set $ns [new Scheduler]) - $ns mrtproto type - type: CtrMcast, DM, ST, BST

LINK:
A link is another major compound object in NS. When a user creates a link using a duplex-link member function of a Simulator object, two simplex links in both directions are created as shown in Figure 8.

Figure 8. Link One thing to note is that an output queue of a node is actually implemented as a part of simplex link object. Packets dequeued from a queue are passed to the Delay object that simulates the link delay, and packets dropped at a queue are sent to a Null Agent and are freed there. Finally, the TTL object calculates Time To Live parameters for each packet received and updates the TTL field of the packet. Tracing In NS, network activities are traced around simplex links. If the simulator is directed to trace network activities (specified using $ns trace-all file or $ns namtrace-all file), the links created after the command will have the following trace objects inserted as shown in Figure 9. Users can also specifically create a trace object of type type between the given src and dst nodes using the create-trace {type file src dst} command.

Figure 9. Inserting Trace Objects When each inserted trace object (i.e. EnqT, DeqT, DrpT and RecvT) receives a packet, it writes to the specified trace file without consuming any simulation time, and passes the packet to the next network object. The trace format will be examined in the General Analysis Example section. Queue Monitor

Basically, tracing objects are designed to record packet arrival time at which they are located. Although a user gets enough information from the trace, he or she might be interested in what is going on inside a specific output queue. For example, a user interested in RED queue behavior may want to measure the dynamics of average queue size and current queue size of a specific RED queue (i.e. need for queue monitoring). Queue monitoring can be achieved using queue monitor objects and snoop queue objects as shown in Figure 10.

Figure 10. Monitoring Queue

When a packet arrives, a snoop queue object notifies the queue monitor object of this event. The queue monitor using this information monitors the queue. A RED queue monitoring example is shown in the RED Queue Monitor Example section. Note that snoop queue objects can be used in parallel with tracing objects even though it is not shown in the above figure.

PACKET FLOW EXAMPLE:


Until now, the two most important network components (node and link) were examined. Figure 11 shows internals of an example simulation network setup and packet flow. The network consist of two nodes (n0 and n1) of which the network addresses are 0 and 1 respectively. A TCP agent attached to n0 using port 0 communicates with a TCP sink object attached to n1 port 0. Finally, an FTP application (or traffic source) is attached to the TCP agent, asking to send some amount of data.

Figure 11. Packet Flow Example Note that the above figure does not show the exact behavior of a FTP over TCP. It only shows the detailed internals of simulation network setup and a packet flow.

PACKET:
A NS packet is composed of a stack of headers, and an optional data space (see Figure 12). As briefly mentioned in the "Simple Simulation Example" section, a packet header format is initialized when a Simulator object is created, where a stack of all registered (or possibly useable) headers, such as the common header that is commonly used by any objects as needed, IP header, TCP header, RTP header (UDP uses RTP header) and trace header, is defined, and the offset of each header in the stack is recorded. What this means is that whether or not a specific header is used, a stack composed of all registered headers is created when a packet is allocated by an agent, and a network object can access any header in the stack of a packet it processes using the corresponding offset value.

Figure 12. NS Packet Format Usually, a packet only has the header stack (and a data space pointer that is null). Although a packet can carry actual data (from an application) by allocating a data space, very few application and agent implementations support this. This is because it is meaningless to carry data around in a non-real-time simulation. However, if you want to implement an application that talks to another application cross the network, you might want to use this feature with a little modification in the underlying agent implementation. Another possible approach would be creating a new header for the application and modifying the underlying agent to write data received from the application to the new header. The second approach is shown as an example in a later section called "Add New Application and Agent".

RESULT:
Thus the details about NS2(Network Simulator 2) has been studied.

Ex. No:11 Date:


AIM:

STUDY OF OPNET

To study about OPNET - Network Simulator

INTRODUCTION:
OPNET (Optimized Network Engineering Tools) is a commercial tool from MIL3 Inc. It is being developed for almost 15 years. As everyone should guess, no much technical detail are available about the internals. USE: Network with several hundreds of nodes can be simulated, but it would take time for the computation. OPNET is used by companies like Thomson-CSF or CNET which use it to model ATM networks and validate various layers protocols, packet switched radio networks. An example of use of OPNET is George Mason University (Quality of Service IP Network Simulation). THE PACKAGE The software comprises several tools and is divided in several parts, OPNET Modeler and OPNET Planner, the Model Library, and the Analysis tool. Features included in this generic simulator are an event-driven scheduled simulation kernel, integrated analysis tools for interpreting and synthesizing output data, graphical specification of models and a hierarchical object-based modeling. OPNET Modeler is intended for modeling, simulating and analyzing the performance of large communications networks, computer systems and applications. Common uses are assessing and feasibility of new designs, optimizing already developed communication systems and predicting performance. The modeling methodology of OPNET is organized in a hierarchical structure. At the lowest level, Process models are structured as a finite state machine. State and transitions are specified graphically using state-transition diagrams whereas conditions that specify what

happen within each state are programmed with a C-like language called Proto-C. Those processes and built-in modules in OPNET (source and destination modules, traffic generators, queues, ...) are then configured with menus and organized into data flow diagrams that represent nodes using the graphical Node Editor. Using a graphical Network Editor, nodes and links are selected to build up the topology of a communication network. The Analysis Tool provides a graphical environment to view and manipulate data collected during simulation runs. Results can be analyzed for any network element. OPNET Planner is an application that allows administrators to evaluate the performance of communications networks and distributed systems, without programming or compiling. Planner analyses behavior and performance by discrete-event simulations. Models are built using a graphical interface. The user only chooses pre-defined models (from the physical layer to the application) from the library and sets attributes. The user cannot define new models, he should contact MIL3's modeling service. The modeling libraries are included with OPNET Modeler and OPNET Planner and contains protocols and analysis environments, among them ATM, TCP, IP, Frame Relay, FDDI, Ethernet, link models such as point-to-point or bus, queueing service disciplines such as First-inFirst-Out (FIFO), Last-In-First-Out (LIFO), priority non-preemptive queueing, shortest first job, round-robin or preempt and resume. OPNET Modeler is the industry's leading environment for network modeling and simulation, allowing you to design and study communication networks, devices, protocols, and applications with unmatched flexibility and scalability. Modeler is used by the world's largest network equipment manufacturers to accelerate the R&D of network devices and technologies such as VoIP, TCP, OSPFv3, MPLS, IPv6, and more. Networking technology has become too complex for traditional analytical methods or "rules of thumb" to yield an accurate understanding of system behavior. Since 1986, OPNET Technologies Inc., has been the leader in developing predictive software solutions for networking professionals. OPNET software enables its users to optimize the performance and maximize the availability of communications networks and applications. OPNET is the state-of-art network simulation tool for modeling, simulating and analysing the performance of i. Communication Networks, Distributed Systems ii. Computer systems and Applications.

Product modules provide value-added capabilities to OPNET's intelligent network management software. Modules span a wide range of applications and receive regular updates under OPNET's maintenance program. OPNET MODULES: Modeler Terrain Modeling Module (TMM) High Level Architecture (HLA) MODELER:

OPNET Modeler is intended for modeling, simulating and analysing the performance of large communications networks, computer systems and applications. Common uses are assessing and feasibility of new designs, optimizing already developed communication systems and predicting performance. The modeling methodology of OPNET is organized in a hierarchical structure. At the lowest level, Process models are structured as a finite state machine. State and transitions are specified graphically using state-transition diagrams whereas conditions that specify what happen within each state are programmed with a C-like language called Proto-C. Those processes, and built-in modules in OPNET (source and destination modules, traffic generators, queues, ...) are then configured with menus and organized into data flow diagrams that represent nodes using the graphical Node Editor. Using a graphical Network Editor, nodes and links are selected to build up the topology of a communication network.

TERRAIN MODELING MODULE (TMM) Building on the capabilities of OPNET's Wireless Module, the Terrain Modeling Module provides the next level of accuracy and control for wireless network design and planning. This module allows you to model environmental effects on wireless network communications anywhere. Featuring an open-source Longley-Rice model, the Terrain Modeling Module is ready to replicate any known atmospheric or topological conditions and their combined impact on signal propagation. Create elevation maps, line-of-sight profiles, and signal-power comparisons of mobile network models. Interfaces to read DTED and USGS DEM terrain data are provided. Open and flexible, the Terrain Modeling Module is supported by the standard Radio Transceiver Pipeline, which enables easy implementation of custom propagation models HIGH LEVEL ARCHITECTURE (HLA) The High-Level Architecture (HLA) Module supports building and running a federation of many simulators, each modeling some aspect of a composite system. The OPNET HLA Module enables OPNET simulations to model some portion (or the entirety) of the communications aspects of the HLA federation models. The OPNET-HLA interface provides the various simulators (federates) the necessary mechanisms to share a common object representation (for persistent elements), to exchange messages (interactions), and to maintain appropriate time synchronization. The module supports a large subset of the HLA interface, including: Time management such that an OPNET simulation remains synchronized with overall HLA time Generation and reception of RTI interactions using OPNET packet Creation, destruction, or discovery of RTI objects during the simulation Generation of RTI object attribute updates based on changes to OPNET attribute values

Automatic updates of OPNET attributes upon reception of RTI object attribute updates A user-defined mapping specifying the relation between RTI and OPNET objects

RESULT:
Thus the Network Simulator-OPNET has been studied.

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