Post on 24-Oct-2014
Location Based Routing For Mobile Ad-Hoc Networks
SCOPE OF THE PROJECT:
An ad-hoc mobile network is a collection of mobile nodes that are dynamically
and arbitrarily located in such a manner that the interconnections between nodes are capable of
changing on a continual basis. The primary goal of such an ad-hoc network routing protocol is
correct and efficient route establishment between a pair of nodes so that messages may be
delivered in a timely manner. LAR is an on-demand protocol which is based on the
DSR(Dynamic Source Routing). The Location Aided Routing protocol uses location information
to reduce routing overhead of the ad-hoc network! Normally the LAR protocol uses the
GPS(Gloal Positioning System) to get these location informations. With the availability of GPS,
the mobile hosts knows there physical location.
Ad hoc networks are a new wireless networking paradigm for mobile hosts. Unlike
traditional mobile wireless networks, ad hoc networks do not rely on any fixed infrastructure.
Instead, hosts rely on each other to keep the network connected. The military tactical and other
security-sensitive operations are still the main applications of ad hoc networks, although there is a
trend to adopt ad hoc networks for commercial uses due to their unique properties. One main
challenge in design of these networks is their vulnerability to security attacks. In this paper, we
study the threats an ad hoc network faces and the security goals to be achieved. We identify the
new challenges and opportunities posed by this new networking environment and explore new
approaches to secure its communication. In particular, we take advantage of the inherent
redundancy in ad hoc networks — multiple routes between nodes — to defend routing against
denial of service attacks. We also use replication and new cryptographic schemes, such as
threshold cryptography, to build a highly secure and highly available key management service,
which forms the core of our security framework.
1
Ad hoc networks are a new paradigm of wireless communication for mobile hosts (which we call
nodes). In an ad hoc network, there is no fixed infrastructure such as base stations or mobile
switching centers. Mobile nodes that are within each other’s radio range communicate directly
via wireless links, while those that are far apart rely on other nodes to relay messages as routers.
Node mobility in an ad hoc network causes frequent changes of the network topology. Figure 1
shows such an example: initially, nodes A and D have a direct link between them. When D moves
out of A’s radio range, the link is broken. However, the network is still connected, because A can
reach D through C, E, and F. Military tactical operations are still the main application of ad hoc
networks today. For example, military units (e.g., soldiers, tanks, or planes), equipped with
wireless communication devices, could form an ad hoc network when they roam in a battlefield.
Ad hoc networks can also be used for emergency, law enforcement, and rescue missions. Since an
ad hoc network can be deployed rapidly with relatively low cost, it becomes an attractive option
for commercial uses such as sensor networks or virtual classrooms.
EXISTING SYSTEM
2
Infra-structured Networks
The first one is to introduce a third fixed party (a base station) that will hand over the
offered traffic from a station to another, as illustrated in Figure 1. The same entity will regulate
the attribution of radio resources, for instance. When a node S wishes to communicate to a node
D, the former notifies the base station, which eventually establishes a communication with the
destination node. At this point, the communicating nodes do not need to know of a route for one
to each other. All that matters is that both nodes source and destination are within the
transmission range of the base station. If one of them fails to fulfill this condition, the
communication will abort.
BASE STATION
S D
E (OUT OF RANGE)
3
Infra structured Network
Here the base station’s range is illustrated by the oval. The two nodes S and D which want to
communicate are in the range of the base station. S send the message to the base station which in
turn forwards it to destination node D. Thus communication is carried out with help of a base
station. All messages have to pass through the base station. Node E is out of the range of the base
station this prevents it from communicating to other nodes in the network. When node E wants to
communicate to any node in the network it has to contact the base station. Since it is out of range
communication is not possible.
What happens if the base station is unavailable? Or what happens if we are in a situation where
such an infrastructure does not exist at the first place?
The answer is that we simply do not communicate! This is where the second approach is useful.
JNote however that this form of centralized administration is very popular among wide cellular
networks such as GSM etc.
PROPOSED SYSTEM
4
Infra-structure-less Networks (Ad Hoc)
The second approach, called the Ad-Hoc, does not rely on any stationary infra structure.
The concept behind these infra-structureless networks is the collaboration between its
participating members, i.e, instead of making data transit through a fixed base station, nodes
consequentially forward data packets from one to another until a destination node is finally
reached. Typically, a packet may travel through a number of network points before arriving at its
destination.
Ad-hoc networking introduces a completely new flavor of network formation. The term Ad-Hoc
means, in this instance, a type instantaneous network connecting various mobile devices without
the intervention of fixed infrastructure. The routers and hosts are free to move randomly and
organize themselves in an arbitrary fashion, thus the network topology changes rapidly and
unpredictably. Absence of a supporting structure in mobile ad-hoc networks, to a certain extent,
invalidates almost all of the existing techniques developed for routine network controls in the
existing wireless networks.
A MANET consists of mobile platforms (e.g., a router with multiple hosts and wireless
communications devices)--herein simply referred to as "nodes"--which are free to move about
arbitrarily. The nodes may be located in or on airplanes, ships, trucks, cars, perhaps even on
people or very small devices, and there may be multiple hosts per router. A MANET is an
autonomous system of mobile nodes. The system may operate in isolation, or may have gateways
to and interface with a fixed network.
5
Infra-structure less Network
Here the node S wants to communicate to node D. The oval indicates the communication range of
the node. The communication range of S does not exceed to include D. In this case routing is
necessary, node E is in the range of S which has D in its range. So S in order to communicate to
D, first sends the message to E which inturn forwards it to D. Thus the node E acts as a router and
a node.
Thus in this way the Ad Hoc network co-operates to forward packets for each other to
communicate without the help of a base station. But there are several issues like selfish nodes,
malicious behavior, routing challenges, security etc.
6
Structure of the network
MANET nodes are equipped with wireless transmitters and receivers using antennas
which may be omnidirectional (broadcast), highly directional (point-to-point), possibly steerable,
or some combination thereof. At a given point in time, depending on the nodes' positions and
their transmitter and receiver coverage patterns, transmission power levels and co-channel
interference levels, a wireless connectivity in the form of a random, multi hop graph or "Ad Hoc"
network exists between the nodes. This ad hoc topology may change with time as the nodes
move or adjust their transmission and reception parameters.
Network Structure
Antenna Node S
Message
Node D
Antenna
The communication is through the antennas attached. The radio range of the node is the range of
communication. Messages are transmitted through the antennas and are received by antennas.
7
Characteristics
MANETs have several salient characteristics:
Dynamic topologies: Nodes are free to move arbitrarily. Thus, the network topology--which is
typically multihop--may change randomly and rapidly at unpredictable times, and may consist of
both bidirectional and unidirectional links.
Bandwidth-constrained, variable capacity links: Wireless links will continue to have
significantly lower capacity than their hardwired counterparts. In addition, the realized
throughput of wireless communications--after accounting for the effects of multiple access,
fading, noise, and interference conditions, etc.--is often much less than a radio's maximum
transmission rate.
One effect of the relatively low to moderate link capacities is that congestion is typically the
norm rather than the exception, i.e. aggregate application demand will likely approach or exceed
network capacity frequently. As the mobile network is often simply an extension of the fixed
network infrastructure, mobile ad hoc users will demand similar services. These demands will
continue to increase as multimedia computing and collaborative networking applications rise.
Energy-constrained operation: Some or all of the nodes in a MANET may rely on batteries or
other exhaustible means for their energy. For these nodes, the most important system design
criteriafor optimization may be energy conservation.
8
Limited physical security: Mobile wireless networks are generally more prone to physical
security threats than are fixed-cable nets. The increased possibility of eavesdropping, spoofing,
and denial-of-service attacks should be carefully considered.
Existing link security techniques are often applied within wireless networks to reduce security
threats. As a benefit, the decentralized nature of network control in MANETs provides additional
robustness against the single points of failure of more centralized approaches.
Routing
A routing protocol is necessary, since two hosts that may wish to exchange packets might
not be able to communicate directly. For example, Figure illustrates a simple ad hoc network of
mobile hosts using wireless network interfaces. Host C is not within the range of host A’s
wireless transmitter and host A is not within the range of host C’s wireless transmitter. If A and C
wish to exchange packets, they may in this case enlist the services of other hosts to forward
packets for them. In this example they use the services of three hosts to communicate. The
maximum number of network hops needed to reach another mobile host in any practical ad hoc
network is likely to be small, but may often be greater than one as shown here. The routing
problem in a real ad hoc network may be even more complicated than this example suggests, due
to the inherent non uniform propagation characteristics of wireless transmission, and since any or
all of the hosts involved may move at any time.
9
Host C
Host A
An Example of Routing
Routing protocols for ad hoc networks can generally be divided into two categories.
A proactive (or periodic) routing protocol attempts to allow each node using it to always
maintain an up-to date route to each possible destination in the network; the protocol periodically
exchanges routing information with other nodes in order to allow new routes to be discovered and
existing routes to be modified if they break due to factors such as node mobility and
environmental changes.
10
Examples:
Link state Routing
DSDV – Destination Sequenced Distance Vector Routing
A reactive (or on-demand) routing protocol only attempts to a discover a route to some
destination when it has a packet to route to that destination and does not already know a route
there; the protocol caches known routes and uses a flooding based discovery protocol when a
needed route is not found in the cache. For dynamically mobile ad hoc networks, reactive or on-
demand routing protocols often outperform proactive or periodic ones, due to their ability to
adjust the amount of network overhead created to track the mobility in the network affecting
current communication.
Examples:
AODV – Ad hoc On Demand Distance Vector Routing
DSR – Dynamic Source Routing.
Route Discovery
When some source node originates a new packet addressed to some destination node, the
source node places in the header of the packet a "source route" giving the sequence of hops that
the packet is to follow on its way to the destination. Normally, the sender will obtain a suitable
source route by searching its "Route Cache" of routes previously learned; if no route is found in
its cache, it will initiate the Route Discovery protocol to dynamically find a new route to this
destination node. In this case, we call the source node the "initiator" and the destination node the
"target" of the Route Discovery.
11
For example, suppose a node A is attempting to discover a route to node E. The Route Discovery
initiated by node A in this example would proceed as follows:
^ "A" ^ "A,B" ^ "A,B,C" ^ "A,B,C,D"
| id=2 | id=2 | id=2 | id=2
+-----+ +-----+ +-----+ +-----+ +-----+
| A |---->| B |---->| C |---->| D |---->| E |
+-----+ +-----+ +-----+ +-----+ +-----+
| | | |
v v v v
Route Discovery
To initiate the Route Discovery, node A transmits a "Route Request" as a single local broadcast
packet, which is received by (approximately) all nodes currently within wireless transmission
range of A, including node B in this example. Each Route Request identifies the initiator and
target of the Route Discovery, and also contains a unique request identification (2, in this
example), determined by the initiator of the Request. Each Route Request also contains a record
listing the address of each intermediate node through which this particular copy of the Route
Request has been forwarded. This route record is initialized to an empty list by the initiator of the
Route Discovery. In this example, the route record initially lists only node A.
When another node receives this Route Request (such as node B in this example), if it is the
target of the Route Discovery, it returns a "Route Reply" to the initiator of the Route Discovery,
giving a copy of the accumulated route record from the Route Request; when the initiator
receives this Route Reply, it caches this route in its Route Cache for use in sending subsequent
packets to this destination.
Otherwise, if this node receiving the Route Request has recently seen another Route Request
message from this initiator bearing this same request identification and target address, or if this
node's own address is already listed in the route record in the Route Request, this node discards
12
the Request. Otherwise, this node appends its own address to the route record in the Route
Request and propagates it by transmitting it as a local broadcast packet (with the same request
identification). In this example, node B broadcast the Route Request, which is received by node
C; nodes C and D each also, in turn, broadcast the Request, resulting in a copy of the Request
being received by node E.
In returning the Route Reply to the initiator of the Route Discovery, such as in this example, node
E replying back to node A, node E will typically examine its own Route Cache for a route back to
A, and if found, will use it for the source route for delivery of the packet containing the Route
Reply. Otherwise, E SHOULD perform its own Route Discovery for target node A, but to avoid
possible infinite recursion of Route Discoveries, it MUST piggyback this Route Reply on the
packet containing its own Route Request for A. It is also possible to piggyback other small data
packets, such as a TCP SYN packet, on a Route Request using this same mechanism.
Node E could instead simply reverse the sequence of hops in the route record that it is trying to
send in the Route Reply, and use this as the source route on the packet carrying the Route Reply
itself. For MAC protocols such as IEEE 802.11 that require a bidirectional frame exchange as
part of the MAC protocol [13], the discovered source route MUST be reversed in this way to
return the Route Reply since it tests the discovered route to ensure it is bidirectional before the
Route Discovery initiator begins using the route; this route reversal also avoids the overhead of a
possible second Route Discovery.
However, this route reversal technique will prevent the discovery of routes using unidirectional
links, and in wireless environments where the use of unidirectional links is permitted, such routes
may in some cases be more efficient than those with only bidirectional links, or they may be the
only way to achieve connectivity to the target node.
13
When initiating a Route Discovery, the sending node saves a copy of the original packet (that
triggered the Discovery) in a local buffer called the "Send Buffer". The Send Buffer contains a
copy of each packet that cannot be transmitted by this node because it does not yet have a source
route to the packet's destination. Each packet in the Send Buffer is logically associated with the
time that it was placed into the Send Buffer and is discarded after residing in the Send Buffer for
some timeout period; if necessary for preventing the Send Buffer from overflowing, a FIFO or
other replacement strategy MAY also be used to evict packets even before they expire.
While a packet remains in the Send Buffer, the node SHOULD occasionally initiate a new Route
Discovery for the packet's destination address. However, the node MUST limit the rate at which
such new Route Discoveries for the same address are initiated, since it is possible that the
destination node is not currently reachable. In particular, due to the limited wireless transmission
range and the movement of the nodes in the network, the network may at times become
partitioned, meaning that there is currently no sequence of nodes through which a packet could be
forwarded to reach the destination. Depending on the movement pattern and the density of nodes
in the network, such network partitions may be rare or may be common.
If a new Route Discovery was initiated for each packet sent by anode in such a partitioned
network, a large number of unproductive Route Request packets would be propagated throughout
the subset of the ad hoc network reachable from this node. In order to reduce the overhead from
such Route Discoveries, a node SHOULD use an exponential back-off algorithm to limit the rate
at which it initiates new Route Discoveries for the same target, doubling the timeout between
each successive Discovery initiated for the same target. If the node attempts to send additional
data packets to this same destination node more frequently than this limit, the subsequent
packets SHOULD be buffered in the Send Buffer until a Route Reply is received giving a route
14
to this destination, but the node MUST NOT initiate a new Route Discovery until the minimum
allowable interval between new Route Discoveries for this target has been reached. This
limitation on the maximum rate of Route Discoveries for the same target is similar to the
mechanism required by Internet nodes to limit the rate at which ARP Requests are sent for any
single target IP address.
Route Maintenance
When originating or forwarding a packet using a source route, each node transmitting the
packet is responsible for confirming that data can flow over the link from that node to the next
hop. For example, in the situation shown below, node A has originated a packet for node E using
a source route through intermediate nodes B, C, and D:
+-----+ +-----+ +-----+ +-----+ +-----+
| A |---->| B |---->| C |-->? | D | | E |
+-----+ +-----+ +-----+ +-----+ +-----+
Route Maintenance
In this case, node A is responsible for the link from A to B, node B is responsible for the link
from B to C, node C is responsible for the link from C to D, node D is responsible for the link
from D to E.
An acknowledgement can provide confirmation that a link is capable of carrying data, and in
wireless networks, acknowledgements are often provided at no cost, either as an existing standard
part of the MAC protocol in use (such as the link-layer acknowledgement frame defined by IEEE
802.11), or by a "passive acknowledgement" (in which, for example, B confirms receipt at C by
overhearing C transmit the packet when forwarding it on to D).
15
If a built-in acknowledgement mechanism is not available, the node transmitting the packet can
explicitly request a DSR-specific software acknowledgement be returned by the next node along
the route; this software acknowledgement will normally be transmitted directly to the sending
node, but if the link between these two nodes is unidirectional, this software acknowledgement
could travel over a different, multi-hop path.
After an acknowledgement has been received from some neighbor, a node MAY choose to not
require acknowledgements from that neighbor for a brief period of time, unless the network
interface connecting a node to that neighbor always receives an acknowledgement in response to
unicast traffic.
When a software acknowledgement is used, the acknowledgement request SHOULD be
retransmitted up to a maximum number of times. A retransmission of the acknowledgement
request can be sent as a separate packet, piggybacked on a retransmission of the original data
packet, or piggybacked on any packet with the same next-hop destination that does not also
contain a software acknowledgement.
After the acknowledgement request has been retransmitted the maximum number of times, if no
acknowledgement has been received, then the sender treats the link to this next-hop destination as
currently "broken". It SHOULD remove this link from its Route Cache and SHOULD return a
"Route Error" to each node that has sent a packet routed over that link since an acknowledgement
was last received.
For example, in the situation shown above, if C does not receive an acknowledgement from D
after some number of requests, it would return a Route Error to A, as well as any other node that
may have used the link from C to D since C last received an acknowledgement from D. Node A
then removes this broken link from its cache; any retransmission of the original packet can be
performed by upper layer protocols such as TCP, if necessary. For sending such a retransmission
16
or other packets to this same destination E, if A has in its Route Cache another route to E (for
example, from additional Route Replies from its earlier Route Discovery, or from having
overheard sufficient routing information from other packets), it can send the packet using the new
route immediately. Otherwise, it SHOULD perform a new Route Discovery for this target.
DATA SECURITY:
i) Message Encryption
ii) Message Decryption
DATA SECURITY USING RSA
Source sends the encrypted data packet to the destination through the route discovered.
Destination decrypts the data packet received from the source and sends the
acknowledgement.
Input and Output ParametersInput and Output Parameters
Input parametersInput parameters
At source, encrypted data packets are sent with destination address and route request.At source, encrypted data packets are sent with destination address and route request.
Output parametersOutput parameters
Receiving positive acknowledgement with efficient and reliable packet transmission.Receiving positive acknowledgement with efficient and reliable packet transmission.
17
ALGORITHM USED
DATA SECURITY USING RSA
Source sends the encrypted data packet to the destination through the route discovered.
Destination decrypts the data packet received from the source and sends the
acknowledgement.
Key Generation:
i. Select two prime numbers p and q such that p
not equal to q.
ii. Calculate n=p x q
iii. Calculate ø (n)=(p-1)(q-1)
iv. Select integer e such that
gcd (ø(n),e)=1;1<e< ø (n)
v. Calculate d such that d=e¹mod ø(n)
vi. Public key KU={e,n}
vii. Private key KR={d,n}
Encryption:
The plain text M (M<n) is encrypted to cipher text using public key e.
C=M pow e (mod n)
Decryption:
The cipher text C is decrypted to plain text using private key d.
M=C pow d (mod n)
18
ALGORITH STEP BY STEP DESCRIPTION:
1. If the user wants to send data:
o Get the Destination identifier and the encrypted data to be transferred.
o Initialize the buffer with the encrypted data to be transferred.
o Setup a Request Zone.
o Build a Route Request packet having the information about the source and the
Destination identifiers, and the Request Zone information.
o Broadcast the Route Request to its neighbors.
o Setup a timer for receiving Route Reply.
2. If the node receives a packet
a. Find the type of the packet received.
b. Depending on the type of packet received do one of the following processes.
Process Route Request.
Process Route Reply.
Process Data Packet.
Process Decryption.
Process Acknowledgement.
Process Route Disconnect.
Process Route Disconnect reply.
Process Timer Run Out.
REQUIREMENT SPECIFICATION
19
Software Requirements
Language : Dot Net
Front End Tool: ASP. Net
Back End Tool: SQL Server
Operating System: Windows 98.
Hardware Requirements
Processor : Intel Pentium III Processor
Random Memory: 128MB
Hard Disk :20GB
Processor Speed: 300 min
20
Location Aided Routing
Route discovery
Route Maintenance
Find request zone and send
route request to all nodes in that
zone
Retrieve route path from
destination
Send & receive data using that
path
Retrieved route path
is not found
DATA FLOW DIAGRAMSDATA FLOW DIAGRAMS
21
22
Get Destination IP and data
Setup Request Zone
Setup a timer and Send Route
Request
FLOW CHARTSFLOW CHARTS
Process Send First Route Request:
Software Description
WHAT IS JAVA?
Java ha two things: a programming language and a platform.
Java is a high-level programming language that is all of the following
Simple Architecture-neutral
Object-oriented Portable
Distributed High-performance
Interpreted multithreaded
Robust Dynamic
Secure
Java is also unusual in that each Java program is both compiled and interpreted. With a compile you translate a Java program into an intermediate language called Java bytecodes the platform-independent code instruction is passed and run on the computer.
Compilation happens just once; interpretation occurs each time the program is executed. The figure illustrates how this works.
23
You can think of Java byte codes as the machine code instructions for the Java Virtual Machine (Java VM). Every Java interpreter, whether it’s a Java development tool or a Web browser that can run Java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware.
Java byte codes help make “write once, run anywhere” possible. You can compile your Java program into byte codes on my platform that has a Java compiler. The byte codes can then be run any implementation of the Java VM. For example, the same Java program can run Windows NT, Solaris, and Macintosh.
JAVA PLATFORM
A platform is the hardware of software environment in which a program runs. The Java platform differs from most other platforms in that it’s a software only platform that runs on the top of other, hardware-based platform. Most other platforms are described as a combination of hardware and operating system.
Java Program
Compilers
Interpreter
My Program
24
The Java platform has two components:
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)
You’ve already been introduced to the Java VM. It’s the base for the Java platform and is ported onto various hardware-based platforms.
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
The Java API is grouped into libraries (package) of related components. The next sections, what can Java do? Highlights each area of functionally provided by the package in the Java API.
The following figure depicts a Java program, such as an application or applet, that’s running on the Java platform. A special kind of application known
as a server serves and supports clients on a network. Examples of the servers include Web Servers, proxy servers, mail servers, print servers, and boot servers. Another specialized program is a Servlet. Servlets are similar to applets in that they are runtime extensions of the application. Instead of working in browsers, though, servlets run with in Java Web Servers, configuring of tailoring the server.
How does the Java API support all of these kinds of programs? With packages of software components that provide a wide range of functionality. The API is the API included in every full implementation of the platform.
The core API gives you the following features:
25
The Essentials: Objects, Strings, threads, numbers, input and output, datastructures, system properties, date and time, and so on.
Applets: The set of conventions used by Java applets.
Networking: URL’s TCP and UDP sockets and IP addresses.
Internationalization: Help for writing programs that can be localized for users.
Worldwide programs can automatically adapt to specific locates and be displayed in the appropriate language.
JAVA PROGRAM
Java API
Java Virtual Machine
Java Program
Hard Ware
API and Virtual Machine insulates the Java program from hardware dependencies. As a platform-independent environment, Java can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and Just-in-time-byte-code compilers can bring Java’s performance close to the native code without threatening portability.
26
WHAT CAN JAVA DO?
However, Java is not just for writing cut, entertaining applets for the World Wide Web (WWW). Java is a general purpose, high-level programming language and a powerful software platform. Using the fineries Java API,you can write many types of programs.
The most common types of program are probably applets and application, where a Java application is a standalone program that runs directly on the Java platform.
Security:
Both low-level and high-level, including electronic signatures, public/private key management, accesses control, and certificate.
27
Networking
Introduction
This article is about a client/server multi-threaded socket class. The thread is optional since the developer is still responsible to decide if needs it. There are other Socket classes here and other places over the Internet but none of them can provide feedback (event detection) to your application like this one does. It provides you with the following events detection: connection established, connection dropped, connection failed and data reception (including 0 byte packet).
Description
This article presents a new socket class which supports both TCP and UDP communication. But it provides some advantages compared to other classes that you may find here or on some other Socket Programming articles. First of all, this class doesn't have any limitation like the need to provide a window handle to be used. This limitation is bad if all you want is a simple console application. So this library doesn't have such a limitation. It also provides threading support automatically for you, which handles the socket connection and disconnection to a peer. It also features some options not yet found in any socket classes that I have seen so far. It supports both client and server sockets. A server socket can be referred as to a socket that can accept many connections. And a client socket is a socket that is connected to server socket. You may still use this class to communicate between two applications without establishing a connection. In the latter case, you will want to create two UDP server sockets (one for each application). This class also helps reduce coding need to create chat-like applications and IPC (Inter-Process Communication) between two or more applications (processes). Reliable communication between two peers is also supported with TCP/IP with error handling. You may want to use the smart addressing operation to control the destination of the data being transmitted (UDP only). TCP operation of this class deals only with communication between two peers.
28
Analysis of Network Client Server
TCP/IP stack
The TCP/IP stack is shorter than the OSI one:
TCP is a connection-oriented protocol; UDP (User Datagram Protocol) is a connectionless protocol.
IP datagram’s
The IP layer provides a connectionless and unreliable delivery system. It considers each datagram independently of the others. Any association between datagram must be supplied by the higher layers. The IP layer supplies a checksum that includes its own header. The header includes the source and destination addresses. The IP layer handles routing through an Internet. It is also responsible for breaking up large datagram into smaller ones for transmission and reassembling them at the other end.
29
UDP
UDP is also connectionless and unreliable. What it adds to IP is a checksum for the contents of the datagram and port numbers. These are used to give a client/server model - see later.
TCP
TCP supplies logic to give a reliable connection-oriented protocol above IP. It provides a virtual circuit that two processes can use to communicate.
Internet addresses
In order to use a service, you must be able to find it. The Internet uses an address scheme for machines so that they can be located. The address is a 32 bit integer which gives the IP address. This encodes a network ID and more addressing. The network ID falls into various classes according to the size of the network address.
Network address
Class A uses 8 bits for the network address with 24 bits left over for other addressing. Class B uses 16 bit network addressing. Class C uses 24 bit network addressing and class D uses all 32.
Subnet address
Internally, the UNIX network is divided into sub networks. Building 11 is currently on one sub network and uses 10-bit addressing, allowing 1024 different hosts.
Host address
8 bits are finally used for host addresses within our subnet. This places a limit of 256 machines that can be on the subnet.
30
Total address
The 32 bit address is usually written as 4 integers separated by dots.
Port addresses
A service exists on a host, and is identified by its port. This is a 16 bit number. To send a message to a server, you send it to the port for that service of the host that it is running on. This is not location transparency! Certain of these ports are "well known".
Sockets
A socket is a data structure maintained by the system to handle network connections. A socket is created using the call socket. It returns an integer that is like a file descriptor. In fact, under Windows, this handle can be used with ReadFile and WriteFile functions.
#include <sys/types.h>#include <sys/socket.h>int socket(int family, int type, int protocol);
Here "family" will be AF_INET for IP communications, protocol will be zero, and type will depend on whether TCP or UDP is used. Two processes wishing to communicate over a network create a socket each. These are similar to two ends of a pipe - but the actual pipe does not yet exist.
31
Module Design Specification
part 1 - Create a server socket that listen for a client to
connect
part 2 - send / receive data from client to server
part 3 - Read unknow size of data from client
32
Create a server socket that listens for a client to connect
socket(int af, int type, int protocol)
This method creates the socket
bind(SOCKET s, const struct sockaddr FAR * name, int namelen)
Associates a local address with a socket This routine is used on an unconnected datagram or stream socket, before subsequent connects or listens. When a socket is created with socket, it exists in a name space (address family), but it has no name assigned. bind establishes the local association (host address/port number) of the socket by assigning a local name to an unnamed socket. In the Internet address family, a name consists of several components. For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts: a host address, the protocol number (set implicitly to UDP or TCP, respectively), and a port number which identifies the application. If an application does not care what address is assigned to it, it may specify an Internet address equal to INADDR_ANY, a port equal to 0, or both. If the Internet address is equal to INADDR_ANY, any appropriate network interface will be used; this simplifies application programming in the presence of multi- homed hosts. If the port is specified as 0, the Windows Sockets implementation will assign a unique port to the application with a value between 1024 and 5000. The application may use getsockname after bind to learn the address that has been assigned to it, but note that getsockname will not necessarily fill in the Internet address until the socket is connected, since several Internet addresses may be valid if the host is multi-homed. If no error occurs, bind returns 0. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError.
listen(SOCKET s, int backlog )
Establishes a socket to listen to a incoming connection To accept connections, a socket is first created with socket, a backlog for incoming connections is specified with listen, and then the connections are accepted with accept. listen applies only to sockets that support connections, i.e. those of type SOCK_STREAM. The socket s is put into "passive'' mode where incoming connections are acknowledged and queued pending acceptance by the process. This function is typically used by servers that could have more than one connection request at a time: if a connection request arrives with
33
the queue full, the client will receive an error with an indication of WSAECONNREFUSED. listen
attempts to continue to function rationally when there are no available descriptors. It will accept connections until the queue is emptied. If descriptors become available, a later call to listen or accept will re-fill the queue to the current or most recent "backlog'', if possible, and resume listening for incoming connections.
accept(SOCKET s, struct sockaddr FAR * addr, int FAR * addrlen)
This routine extracts the first connection on the queue of pending connections on s, creates a new socket with the same properties as s and returns a handle to the new socket. If no pending connections are present on the queue, and the socket is not marked as non- blocking, accept blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue, accept returns an error as described below. The accepted socket may not be used to accept more connections. The original socket remains open. The argument addr is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family in which the communication is occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. This call is used with connection-based socket types such as SOCK_STREAM. If addr and/or addrlen are equal to NULL, then no information about the remote address of the accepted socket is returned.
closesocket(SOCKET s)
closes a socket
Making client connection with server
In order to create a socket that connects to an other socket uses most of the functions from the previous code with the exception of a struct called HOSTENT
HOSTENT:
This struct is used to tell the socket to which computer and port to connect to. These struct can appear as LPHOSTENT, but it actually means that they are pointer to HOSTENT.
34
Client key function
Most of the functions that have been used for the client to connect to the server are the same as the server with the exception of a few. I will just go through the different functions that have been used for the client.
gethostbyname(const char* FAR name)
gethostbyname returns a pointer to a hostent structure as described under gethostbyaddr. The contents of this structure correspond to the hostname name. The pointer which is returned points to a structure which is allocated by the Windows Sockets implementation. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information which it needs before issuing any other Windows Sockets API calls. A gethostbyname implementation must not resolve IP address strings passed to it. Such a request should be treated exactly as if an unknown host name were passed. An application with an IP address string to resolve should use inet_addr to convert the string to an IP address, then gethostbyaddr to obtain the hostent structure.
Part 2 - Send / recieve
Up to this point we have managed to connect with our client to the server. Clearly this is not going to be enough in a real-life application. In this section we are going to look into more details how to use the send/recv functions in order to get some communication going between the two applications.
Factually this is not going to be difficult because most of the hard work has been done setting up the server and the client app. before going into the code we are going to look into more details the two functions
send(SOCKET s, const char FAR * buf, int len, int flags)
send is used on connected datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSAData structure returned by WSAStartup. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.
35
recv(SOCKET s, const char FAR * buf, int len, int flags)
For sockets of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in- line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application may use the ioctlsocket SIOCATMARK to determine whether any more out-of-band data remains to be read.
part 3 - Read unknow size of data from client
Us mentioned earlier in part 2, we are noe going to expand on the way that we receive data. The problem we had before is that if we did not know the size of data that we where expecting, then the would end up with problems.
In order to fix this here we create a new function that receive a pointer to the client socket, and then read a char at the time, placing each char into a vector until we find the '\n' character that signifies the end of the message.
This solution is clearly not a robust or industrial way the read data from one socket to an other, because but its a way to start reading unknown length strings. the function will be called after the accept method
36