Ans :

When protocols are implemented for computer communication, we encounter some
challenges due to the infrastructure and machines used in computer network may not be
compatible and aligned with one another. The concept of Internetworking though, highly
desirable, is not easily achievable. Let us see one simple example to understand the
compatibility problem, any two networks, cannot directly communicate by connecting a
wire between the networks. For example, one network could represent a binary 0 by-5
volts, another by +5 volts. Similarly, one could use a packet size of 128 bytes, whereas
other could use 256 byte packets. The method of acknowledgement or error detection

could be different. There could be many such differences. The incompatibility issues
are handled at two levels:

i) Hardware Issues
At the hardware level, an additional component called router is used to connect
physically distinct networks. A router connects to the network in the same way as any
other computer. Any computer connected to the network has a Network Interface Card
(NIC), which has the address (network id+ host id), hard coded into it. A router is a
device with more than one NICs. Router can connect incompatible networks as it has the
necessary hardware (NIC) and protocols.

ii) Software Issues

The routers must agree about the way information would be transmitted to the
destination computer on a different network, since the information is likely to travel
through different routers, there must be a predefined standard to which routers must
confirm. Packet formats and addressing mechanism used by the networks may differ.
One approach could be to perform conversion and reconversion corresponding to
different networks. But this approach is difficult and cumbersome. Therefore, the
Internet communication follows one protocol suite, the TCP/IP. The basic idea is that it
defines a packet size, routing algorithms, error control, flow control methods
universally.

It would be unwise to club all these features in a single piece of software ─ it would
make it very bulky. Therefore, all these features are logically sub-grouped and then the
sub-groups are further grouped into groups called layers. Each layer has an interface
with the adjacent layers, and performs specific functions.

 


Ans :

AnalogDigital
Signals are records waveforms as they are.
Signal occupies the same order of spectrum as
the analog data.
Converts analog waveforms into set of numbers
and records them. The numbers are converted
into voltage stream for representation. In case of
binary it is converted in 1’s and 0’s.
In analog systems electronic circuits are used
for transformation of signals.
In this transformation is done using logic
circuits.
About Noise analog signals are more likely to
get affected and results in reducing accuracy
Digital signals are less affected, because noise
response are analog in nature
Analog signal is a continuous signal which
transmits information as a response to changes
in physical phenomenon.
Digital signals are discrete time signals
generated by digital modulation.
Data transmission is not of high qualityData transmission has high quality.
Analog devices are not very precise.Digital systems are very precise.

 The standard mechanism for electronic mail in the Internet is Simple Mail Transfer

Protocol (SMTP). It provides mail and message exchange between TCP/IP hosts.
SMTP is based on end-to-end delivery i.e., an SMTP client contacts the destination
host’s SMTP server directly for delivering the mail. The destination host’s SMTP
server keeps the mail until the mail has been successfully copied into the recipient’s
SMTP. The SMTP is a connection service based on client-server environment and
runs on port number 25 at the server side as shown in the Figure 8. The various
components of SMTP are:

1) Mail Transfer Agent (MTA)
2) User Agent (UA)





 The Dynamic Domain Name System (DDNS) is a protocol that defines extensions to

the DNS in order to enable the DNS servers to accept the requests to add, update and
delete entries in the DNS database dynamically. Because DDNS offers a functional
superset to existing DNS servers, a DDNS server can serve both static and dynamic
domains at the same time. Rather than allowing any host to update its DNS records,
the secure version of DDNS uses public key security and digital signatures to
authenticate update requests from DDNS hosts.

Three common utilities for querying name servers are provided with many DNS
implementations:

1) Host obtains an IP address associated with a host name or a host name associated
with an IP address.

2) Nslookup allows you to locate information about network nodes, examine the
contents of a name server database and establish the accessibility of name servers.

3) Hig allows you to exercise name servers, gather large volumes of domain name
information, and execute simple domain name queries. DIG stands for Domain
Internet Groper.

The following RFCs define the Domain Name System standard and the information
kept in the system:


1) RFC 1032 – Domain Administrator’s Guide
2) RFC 1033 – Domain Administrator Operations Guide
3) RFC 1034 – Domain Names – Concepts and Facilities
4) RFC 1035 – Domain Names – Implementation and Specification
5) RFC 1101 – DNS Encoding of Networks Names and Other Types.

 Ans :

The concept of mapping a domain name to an IP address and vice-versa is known as
resolution process. The resolution process is basically a client server platform.
Whenever a user needs to map an address to a domain or vice-versa, the DNS calls a
client program called resolver. The resolver subsequently contacts the nearest DNS
server (name server) with a request. In case the server has the desired information, it
replies back with the results. Otherwise it suggests the resolver to other domain
servers or asks other servers to provide the desired information. The resolver, after
receiving the results asserts the information and thereafter delivers the desired
information to the specific host process. The steps followed in the resolution are
below

1) The user program issues a request such as the gethostbyname( ) system call. (This
particular call is used to ask for the IP address of a host by passing the host
name as a parameter).

2) The resolver formulates a query to the name server.

3) The name server checks to see if the answer is in its local authoritative database
or cache, and if so, returns it to the client. Otherwise, it will query other available
name server(s), starting down from the root of the DNS tree or as high up the tree
as possible.

4) The user program will finally be given a corresponding IP address (or host name,
depending on the query) or an error if the query could not be answered.
As the resolution process is carried out with the help of queries, these domain name
request queries can be one of two types: recursive or iterative. A flag bit in the
domain name query specifies whether the client desires a recursive query, and a flag
bit in the response specifies whether the server supports recursive queries. A
recursive query requests that the server should itself issue a query to determine the
requested information and return the complete answer to the client. However, an
iterative query means that the name server should return what information it has
available and also a list of additional servers for the client to contact to complete the
query.

The concept of caching is also utilized in DNS. Whenever a name-server receives a
request from a client, the name server subsequently sends the query to other servers.
Later on, when it receives the response, it first stores this information in its own cache
memory before sending the desired information to the client. Now onwards, if any
client desires the same information, first the name-server can simply check its cache
memory and resolve the query. However, such a response is designated as nonauthoritative. The domain name responses from the name server can be one of two
types: authoritative and non-authoritative.

 The hierarchical system of domain names in Internet has been broadly classified into

three categories:

  1. Generic domain names
  2. Country based domain names
  3. Inverse domains

The three-character top-level names are called the generic domains or the
organizational domains. The generic domain defines registered hosts in accordance
with their behavior for example, yahoo.com uses ‘com’ as top level name as it
signifies that yahoo is a commercial organization. Table 1 shows some of the top-level domains of today’s Internet domain hierarchy.

Domain  Name                                 Meaning
Com                     Commercial organizations
Gov                      Government institutions
Org                    Non-profit organizations
Mil                            Military groups
Edu                    Educational institutions

Net                     Major network support centers

Int                       International organizations

There are also top-level domains named for each of the ISO 3166 international 2-
character country codes (e.g., zw for Zimbabwe). These are called the country
domains. Many countries have their own second-level domains underneath, which
parallel the generic top-level domains.

As it is a simple matter in principle to search the database for an IP address with its
symbolic name (because of the hierarchical structure), the reverse process cannot
follow the hierarchy. Therefore, there is another namespace for the reverse mapping
called Inverse domain. The information about the inverse domain is always stored in
the domain “in-addr.arpa”. Here, the IP addresses are stored in a hierarchical form
such that each level of the tree depicts 8 bits of information of IP address. However,
since domain names have the least significant parts of the name first, but dotted
decimal format has the most significant bytes first, the dotted decimal address is
shown in reverse order. For example, the domain in the domain name system
corresponding to the IP address 171.10.1.2 is 2.1.10.171.in-addr.arpa. The above
mapping is carried out by using a special kind of query called inverse pointer query.

 The following is the step by step procedure to configure a Samba Server

  1. Server IP address is xxx.xxx.0.254 and machine name is Server1
  2. Windows machine IP address is xxx.xxx.0.2 and machine name is client2
  3. Firewall Should be disabled.
chkconfig iptables off
service iptables stop
chkconfig ip6tables off
service ip6tables stop

4. To check if all rpms required for samba are installed or not.

              #rpm –qa | grep samba, then it displays the following
             Samba-<version-name>
             Samba-common-<version-name>
             Samba-client-<version-name>
             System-config-samba-<version-name>

5. If not, install it using
                #rpm –ivh samba

6. Copy the original configuration file as smb.conf.bck
               #cp /etc/samba/smb.conf /etc/samba.conf.bck
              (This will keep a backup copy of your configuration file.)

7. Now edit the configuration file
              #vi /etc/samba/smb.conf

8. To share home directory edit this part of /etc/samba/smb.conf

  [homes]

            comment=Home directories
            browseable =no
            writable=yes

9. To share printer edit this part of /etc/samba/smb.conf

  [printers]

           comment = All printers
           path = /var/spool/samba
           browseable = no

10.To configure share called IHNCSHARE edit this part of /etc/samba/smb.conf
[IHNC’s share]
comment = Testing Samba Server
path = /samba
valid users = user1, user2

11. Save the file with wq command

12. To check your configuration file type testparm
#testparm

13. Create two samba users user1 and user2
useradd user1
useradd user2

14. Create smbpassword for both the users
smbpasswd –a user1
smbpasswd –a user2

  1. Now you stop/start the samba services

service smb stop
service smb start

  1. To see what is shared from your server through samba for a particular user

smbclient -L Server1 –U user1 or smbclient –L //xxx.xxx.0.1 –U user1

  1. To see what is shared for a particular host

smbclient –L mac2

  1. Now, permanently make samba server on
    #chkconfig smb on

 

smb.conf is the main Samba configuration file. You find a full commented
version at /usr/share/doc/packages/samba/examples/smb.conf.SUSE if the
samba-doc package is installed.
Date: 2008-05-28
[global]
workgroup = WORKGROUP
printing = cups
printcap name = cups
printcap cache time = 750
cups options = raw
map to guest = Bad User
include = /etc/samba/dhcp.conf
logon path = \%L\profiles.msprofile
logon home = \%L\%U.9xprofile
logon drive = P:
usershare allow guests = Yes
add machine script = /usr/sbin/useradd -c Machine -d /var/lib/nobody -s /bin/false
%m$
domain logons = No
domain master = No
security = user
usershare max shares = 100
[homes]
comment = Home Directories
valid users = %S, %D%w%S
browseable = No
read only = No
inherit acls = Yes

[profiles]
comment = Network Profiles Service
path = %H
read only = No
store dos attributes = Yes
create mask = 0600
directory mask = 0700
[users]
comment = All users
path = /home
read only = No
inherit acls = Yes
veto files = /aquota.user/groups/shares/
[groups]
comment = All groups
path = /home/groups
read only = No
inherit acls = Yes
[printers]
comment = All Printers
path = /var/tmp
printable = Yes
create mask = 0600
browseable = No
[print$]
comment = Printer Drivers
path = /var/lib/samba/drivers
write list = @ntadmin root
force group = ntadmin
create mask = 0664
directory mask = 0775
Share disabled by YaST
[netlogon]
[public]
comment = RAID drive share
inherit acls = Yes
path = /local/public
read only = No

 Configuring an NFS server is straightforward:


Use the chkconfig command to configure the required nfs and RPC rpcbind daemons
to start at boot and also activate NFS file locking to reduce the risk of corrupted data.
The following is the example:

root@# chkconfig nfs on
root@# chkconfig nfslock on
root@# chkconfig rpcbind on
Use the init scripts in the /etc/init.d directory to start the nfs and RPC rpcbind
daemons.

The following are examples to use the start option, but by using stop and restart
options one can stop or restart the service as when needed.

root# service rpcbind start
root# service nfs start
root# service nfslock start

root# service rpcbind stop
root# service rpcbind restart

Test whether NFS is running correctly with the rpcinfo command or not. The
following I an example to list the running RPC programs.

root# rpcinfo -p localhost

program vers proto port

100000 2 tcp 111 portmapper

100000 2 udp 111 portmapper

100003 2 udp 2049 nfs

100003 3 udp 2049 nfs

100021 1 udp 1024 nlockmgr

100021 3 udp 1024 nlockmgr

100021 4 udp 1024 nlockmgr

100005 1 udp 1042 mountd

100005 1 tcp 2342 mountd

100005 2 udp 1042 mountd

100005 2 tcp 2342 mountd


100005 3 udp 1042 mountd

100005 3 tcp 2342 mountd
root#

 The following is the dhcpd.conf file

ddns-update-style interim
ignore client-updates

subnet 192.168.1.0 netmask 255.255.255.0 {

# The range of IP addresses the server
# will issue to DHCP enabled PC clients
# booting up on the network

range 192.168.1.201 192.168.1.220;

# Set the amount of time in seconds that
# a client may keep the IP address
default-lease-time 86400;
max-lease-time 86400;

# Set the default gateway to be used by
# the PC clients

option routers 192.168.1.1;
# Don't forward DHCP requests from this
# NIC interface to any other NIC
# interfaces

option ip-forwarding off;

# Set the broadcast address and subnet mask
# to be used by the DHCP clients

option broadcast-address 192.168.1.255;
option subnet-mask 255.255.255.0;

# Set the NTP server to be used by the
# DHCP clients
option ntp-servers 192.168.1.100;
# Set the DNS server to be used by the
# DHCP clients
option domain-name-servers 192.168.1.100;

# If you specify a WINS server for your Windows clients,

# you need to include the following option in the dhcpd.conf file:
option netbios-name-servers 192.168.1.100;

# You can also assign specific IP addresses based on the clients'
# ethernet MAC address as follows (Host's name is "laser-printer":


host laser-printer {
hardware ethernet 08:00:2b:4c:59:23;
fixed-address 192.168.1.222;
}
}
#
#List an unused interface here
#
subnet 192.168.2.0 netmask 255.255.255.0 {
}

The following are the activities between DHCP Server and DHCP Client.

• Lease Request: Client broadcasts request to DHCP server with a source address
of 0.0.0.0 and a destination address of 255.255.255.255. The request includes the
MAC address which is used to direct the reply.

• IP lease offer: DHCP server replies with an IP address, subnet mask, network
gateway, name of the domain, name servers, duration of the lease and the IP
address of the DHCP server.


• Lease Selection: Client receives offer and broadcasts to al DHCP servers that will
accept given offer so that other DHCP server need not make an offer.

• The DHCP server then sends an acknowledgement to the client. The client is
configured to use TCP/IP.

• Lease Renewal: When half of the lease time has expired, the client will issue a
new request to the DHCP server.

Download and Install the DHCP Package
Most RedHat and Fedora Linux software product packages are available in the RPM
format, whereas Debian and Ubuntu Linux use DEB format installation files. When
searching for these packages, remember that the filename usually starts with the
software package name and is followed by a version number, for example the file
name as ‘dhcp-3.23.58-4.i386.rpm’.

Managing the DHCP daemon is easy to do, but the procedure differs between Linux
distributions. Here are some things to keep in mind.

• Firstly, different Linux distributions use different daemon management systems.
Each system has its own set of commands to do similar operations.

• Secondly, the daemon name needs to be known and in this case the name of the
daemon is DHCP.

dhcpd.conf File

You can define your server configuration parameters in the dhcpd.conf file which
may be located in the /etc the /etc/dhcpd or /etc/dhcp3 directories depending on your
version of Linux.

The dhcpd.conf configuration file formats in Debian / Ubuntu and Redhat / Fedora
are identical.

Here is a quick explanation of the dhcpd.conf file.

 

 Understanding DNS

The basic function of name server is to answer queries by providing the information
that those queries request. A DNS name server primarily translates domain and host
names into IP addresses. Each domain is typically represented by a least two DNS
servers. The following are different types of DNS servers:

• Primary (master) name server contains authoritative information about the
domains that it serves. In response to queries for information about its domains,
this server provides that information marked as being authoritative. The primary
is the ultimate source for data about the domain. The secondary name server only
carries the same authority in that it has received and loaded a complete set of
domain information from the primary.

• Secondary (slave) name server
gets all information for the domain from the
primary. As is the case for the primary, DNS considers the secondary information
about the domain that it serves authoritative.

• Caching name server simply caches the information it receives about the
locations of hosts and domains. It holds information that it obtains from other
authoritative servers and reuses that information until the information expires.

• Forwarding name server is essentially a caching name server but is useful in
cases where computers lie behind a firewall and in which only one computer can
make DNS queries outside that firewall on behalf of all the internal computers.

 NFS isn't a single program, but a suite of interrelated programs that work together to

get the job done. The following are several daemons that are started when a system
goes into run level 3 or multi-user mode. The mounted and nfsd daemons are run on
systems that are servers. The automatic startup of the server daemons depends on the
existence of entries that are labeled with the NFS file-system type in /etc./ds/share tab.
To support NFS file locking, the locked and stated daemons are run on NFS clients and
servers.

i) automounted Daemon

This daemon handles the mounting and unmounting requests from the autos
service. The syntax of the command is as follows:
automounted [ -Tnv ] [ -D name=value ]
The command behaves in the following ways:

-T enables tracing.
-n disables browsing on all autofs nodes.
-v selects to log all status messages to the console.
-D name=value substitutes value for the automount map variable that is
indicated by name.

The default value for the automount map is /etc/auto_master. Use the -T option
for troubleshooting

ii) Lockd Daemon
This daemon supports record-locking operations on NFS files. The lockd daemon
manages RPC connections between the client and the server for the Network
Lock Manager (NLM) protocol.

iii) Mountd Daemon
This daemon handles file-system mount requests from remote systems and
provides access control. The mountd daemon checks /etc/dfs/sharetab to
determine which file systems are available for remote mounting and which
systems are allowed to do the remote mounting. One can use the -v option and the
-r option with this command.

The -v option runs the command in verbose mode. Every time an NFS server
determines the access that a client should be granted, a message is printed on the
console. The information that is generated can be useful when trying to determine
why a client cannot access a file system.

The -r option rejects all future mount requests from clients. This option does not
affect clients that already have a file system mounted.

iv) nfs4cbd Daemon
This daemon is for the exclusive use of the NFS version 4 client that manages the
communication endpoints for the NFS version 4 callback program. The daemon
has no user-accessible interface.

v) nfslogd Daemon
This daemon provides operational logging. NFS operations that are logged
against a server are based on the configuration options that are defined in
/etc/default/nfslogd. When NFS server logging is enabled, records of all RPC
operations on a selected file system are written to a buffer file by the kernel

vi) statd Daemon
This daemon works with lockd daemon to provide crash and recovery functions
for the lock manager. The statd daemon tracks the clients that hold locks on an
NFS server. If a server crashes, on rebooting, statd daemon on the server contacts
statd on the client. The client statd can then attempt to reclaim any locks on the
server. The client statd also informs the server statd when a client has crashed so
that the client's locks on the server can be cleared.

vii) rpcbind: (portmap in older versions of Linux)
The primary daemon upon which all the others rely, rpcbind manages
connections for applications that use the RPC specification. By default, rpcbind
listens to TCP port 111 on which an initial connection is made. This is then used
to negotiate a range of TCP ports, usually above port 1024, to be used for
subsequent data transfers. You need to run rpcbind on both the NFS server and
client.

viii) nfs
Starts the RPC processes needed to serve shared NFS file systems. The nfs
daemon needs to be run on the NFS server only.

ix) nfslock
Used to allow NFS clients to lock files on the server via RPC processes. The
nfslock daemon needs to be run on both the NFS server and client.

x) netfs
It allows RPC processes run on NFS clients to mount NFS filesystems on the
server. The netfs daemon needs to be run on the NFS client only.



 Programs that read and write to files on a local filesystem rely on the operating

system to track their access location within the file with a pointer. As NFS is a
network-based file system, and networks can be unreliable, it was decided that the
NFS client daemon would act as a failsafe intermediary between regular programs
running on the NFS client and the NFS server.

Normally, when a server fails, file accesses timeout and the file pointers are reset to
zero. With NFS, the NFS server doesn't maintain the file pointer information, the
NFS client does. This means that if an NFS server suddenly fails, the NFS client can
precisely restart the file access once more after patiently waiting until the server
returns online.

 VFS interface is the mechanism used by NFS to redirect all access to NFS-mounted

files to the remote server. It is done in such a way that files on the remote NFS server
appear to the user like those on a local disk.

 TCP server, binds to a well-known port and waits for a client to try to connect to it.

This process is called as “listening” and it is performed by calling the listen () system
call.

The Listen system call is used in the server in the case of connection-oriented
communication to prepare a socket to accept messages from clients. It creates a
passive socket (recall the concept of passive and active mode of socket) from an
unconnected socket. ‘Listen’ initializes a queue for waiting connections. Before
calling listen, socket must be created and its address field must be set.

Usually Listen() is executed after both socket() and bind() calls and before accept()
[accept system call will be discussed in next sections].

#include<sys/types.h>
#include<sys/types.h>
int listen(int sockfd, int Max_conn)

On success, listen() returns “0”
On failure, it return
s “-1” and the error is in errno.

Listen takes two parameters, first the socket you would like to listen on and another is
the Maximum number of request that will be accepted on the socket at any given
time. Socket you would like to listen on is represented here as sockfd is the usual
socket file descriptor from the socket() system call. Maximum number of connections
allowed on the incoming queue at any given time is represented by backlog. On the
server all incoming connections requests from clients come and wait in one special
queue (from this queue server choose the connection and accept the request). We
have to define the limit on queue that how many connections can wait in a queue.
Generally this limit is set to 20. But you can set it with any other number also, for
example,

listen (socket, 5), call will inform the operating system that server can only allow
five client sockets to connect at any one given time.

If the queue is full, then the new connection request will be rejected, which will result
in an error in the client application. Queued connections are removed from the queue
and completed with the accept() function, which also creates a new socket for
communicating with the client.

Example :

#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define SERVERPORT 1729
int main()
{
int sockfd;
struct sockaddr_in ser_addr;
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket error");


exit(1);
}

ser_addr.sin_family = AF_INET;
ser_addr.sin_port = htons(SERVERPORT);
ser_addr.sin_addr.s_addr = inet_addr(INADDR_ANY);
memset(&(ser_addr.sin_zero), '\0', 8); /* zero the rest of the struct */
if ( bind(sockfd, (struct sockaddr *)& ser_addr, sizeof(struct sockaddr)) < 0 )

{
perror("bind");
exit(1);
}
if ( listen(sockfd, 5) < 0 ) / * Inform the operating sytem that server cn allow
only 5 clients*/
{
perror("listen error");
exit(1);
}
.
.
.
}

 Ans :

Generally “connect” function is used by client program to establish a connection to a
remote machine (server).

Syntax of connect is given below:

#include<sys/types.h>
#include<sys/socket.h>
int connect(int sockfd, struct sockaddr_in *server_addr, int serv_addrlen);
connect() returns 0 if successful or returns -1 on unsuccessful and sets errno


In the connect call, sockfd is a socket file descriptor returned by socket(), server_addr
points to a structure with destination port and IP address and serv_addrlen set to
sizeof (struct sockaddr).

Initial code necessary for a TCP client:

#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>

#include<netinet/in.h>
#define SERVER_IP "190.20.10.12"
#define SERVER_PORT 1729

main()
{
int sockfd;
struct sockaddr_in ser_addr; /* will hold the destination addr */

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))<0)

{ perror("socket error ");
exit(1);
}

Ser_addr.sin_family = AF_INET; /* inet address family */
Ser_addr.sin_port = htons(SERVER_PORT); /* destination port */
Ser_addr.sin_addr.s_addr = inet_addr(SERVER_IP); /* destination IP address */
memset(&(dest_addr.sin_zero), '\0', 8); /* zero the rest of the struct / *
/* In function void *memset(void *s, int c, size_t n); The memset() function
fills the first n bytes of the memory area pointed to be s with the constant byte c.*/


if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr))<0)
{
perror("connect error");
exit(1);
}

During the bind call example earlier we have ignored the local port number, now we
are concerned about the remote port. The kernel will choose a local port, and the site
we connect to, will automatically get this information from client.

If connectionless client (UDP) use the connect (), then the system call just stores the
server address specified by the process, so that the system knows where to send any
future data the process writes to the sockfd descriptor. Also, the socket will receive
only datagrams from this address. Note that the destination address is not necessary
for each Datagram sent, if we are connecting a UDP socket.

Connect system call result in actual connection establishment between the local and
remote system in case of connection-oriented protocol. At this point some agreement
for the future data exchange happens like buffer size, amount of data,
acknowledgement etc., as we have discussed earlier in Unit 3 of Block 1. This
exchange of information between client and server are known as 3-way handshake,

To use connect function, first of all client needs to call the socket (), then connect ()
function sets value of server socket address and client socket address is either
provided by bind system call or set by the operating system.

 After creating “socket” and before Sending/Receiving data using socket, it must be

associated with a local port and a network interface address. That’s why we can say
mapping of a socket to a port number and IP address is called a “binding”. Why
binding is needed, as you know server use socket so it can attend client request on
specific port. Socket must be associated with particular port on one network interface.
But think when we can have multiple network addresses on one host and each
network, we have some port addresses. In this case with the help of bind we can
define, for which network address (IP address + port address) with which port is
associated, otherwise imagine how much confusion can happen.

#include<sys/types.h>
#include<sys/socket.h>
int bind(int sockfd, struct sockaddr_in *localaddr , intaddrlen);

Here in the above prototype of bind, sockfd is File descriptor of local socket, as
created by the socket function. Localaddr is a pointer to protocol address structure of
local socket. The special address ANY_ADDR can be used to allow the connection to
be made on any of the host’s interfaces and addrlen is indicating length in bytes of
structure referenced by address. On success, bind () returns a zero. On failure, it
returns -1 with an error number.

Use of Bind
During networking programming we find that there are three user of Bind system
call.
A specific network address and port address can be registered to a client.
Server needs to register a specific network & port address with its socket,
basically it informs the system that “The address associated with me is this, and if
you get any message on this address just transfer it to me”.

• In case of connectionless client (see your unit 1 of block 1 to know about
connectionless and connection oriented services), it needs to assure that system
has provided some valid unique addresses, so that when server sends some
message it will reach the desired client. This approach of client is same like us,
when we write letter we always check whether we have written own address on
that envelop or not so that we can get reply on that address.

The bind system call fills the two tuple of association, Local address and Local
process elements. When we will use Bind function the client needs to call socket
system call because it needs to use the returned value as socket descriptor.

When binding is over, then in-case of UDP socket it is ready to send and receive
datagram’s. For TCP sockets, the socket is ready to connect or accept calls. Let’s see
what are these accept and connect call.


Let’s have an example:

#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#define CLIENTPORT 8090

main()
{
int sockfd;
struct sockaddr_in local_addr;


sockfd = socket(AF_INET, SOCK_STREAM, 0);
client_addr.sin_family = AF_INET; /* host byte order */
client_addr.sin_port = htons(CLIENTPORT); /* short, network byte order */
client_addr.sin_addr.s_addr = inet_addr("192.10.10.10");
bzero(&(client_addr.sin_zero), 8); /* zero the rest of the struct */

/* error checking for bind(): */
bind(sockfd, (struct sockaddr *)&client_addr, sizeof(struct sockaddr));
.
.
.
}


In socket programming we have different methods which may be useful to you, when
you want to choose an unused port at random you can write /* choose an unused port
at random */

and for choosing IP address you can use / use client IP address */

 Ans :           
                     As you know socket family defines the protocol group needed for
                    communication. At the time of programming you should choose one of the given

                    options but because we are concerned about TCP/IP you need to remember
                     AF_INET.

                    AF_UNIX /*Unix internal protocols */
                    AF_INET /* internet protocols */
                   AF_NS /* Xerox NS protocols */
                   AF_IMPLINK /* IMP link layer */

 Ans :

1) Source Port Number: A 16-bit number which defines the source port number
for a particular application program that is sending the UDP datagrams.

2) Destination Port Number: A 16-bit number that defines the destination port
number for a particular application program that is receiving the UDP datagrams.

 
Source port number 16 bits                           Destination port number 16 bits
               Length
               16 bits
                                              Check sum
                                                  16 bits
                                                         Data

3) Length : The 16-bit field denotes the size of UDP header combined with payload
data. It can range between 0 to 65,535 bytes.

4) Checksum: This is 16-bit field that provides detection of errors over the entire
user datagram.

Characteristics of UDP
The basic characteristics of UDP are as follows:

  1. UDP is a connectionless service.
  2. It adds no non-reliable flow control to IP.
  3. It serves as a multiplex/demultiplexer for sending and receiving datagrams.
  4. The communication ends (end terminals) need not be synchronized.
  5. There is no provision for acknowledgement of datagrams.

    Applications of UDP
    The standard applications using UDP include:

    1. Trivial File Transfer Protocol (TFTP)
    2. Domain Name System (DNS) name server
    3. Remote Procedure Call (RPC) used by the Network File System (NFS)
    4. Simple Network Management Protocol (SNMP).

    Internet Control Message Protocol (ICMP)
    The Internet Control Message Protocol notifies the sender of IP datagrams about
    abnormal events. ICMP is important in the connectionless environment. ICMP
    messages are carried in IP packets. The most commonly employed ICMP message
    types include:

    1. Destination Unreachable: This message type indicates that a packet cannot be
    delivered because the destination host cannot be reached. The reason for the nondelivered may be that the host or network is unreachable or unknown, the protocol
    or port is unknown or unusable.

    2. Echo and Echo Reply: These two messages are used to check whether hosts are
    reachable on the network. One host sends an Echo message to the other,
    optionally containing some data and the receiving host responds with an Echo
    Reply containing the same data. These messages are the basis for the Ping
    command.

    3. Source Quench: Sent by a router to indicate that it is experiencing congestion
    and is discarding datagrams.

    4. TTL Exceeded:
    This message indicates that a datagram has been discarded
    because the TTL field reached 0 or because the entire packet was not received
    before the fragmentation timer expired.

    5. Timestamp and Timestamp Reply:
    These messages are similar to the Echo
    messages, but place a timestamp (with millisecond granularity) in the message,
    yielding a measure of how long remote systems spend buffering and processing
    datagrams and providing a mechanism so that hosts can synchronize their clocks.

 1) Source Port Number: This is a 16-bit number which defines the source port

number for a particular application program that is sending the TCP segments.

2) Destination Port Number: This is a 16-bit number which defines the
destination port number for a particular application program that is receiving the
TCP segments.

3) Sequence Number: As the unit of data transfer in TCP is termed as segment,
each segment’s first data byte number denotes the 32-bit sequence number. Since
the sequence number refers to a byte count rather than a segment count, sequence
numbers in contiguous TCP segments are not numbered sequentially. For
example, if a file of 5000 bytes is transferred using TCP connection and the first
byte is numbered as 20002 and data divided into 5 segments each of 1000 bytes,
the sequence numbers assigned to various segments are as under:

Segment 1  sequence number: 20002
Segment 2  sequence number: 21002
Segment 3  sequence number: 22002
Segment 4  sequence number: 23002
Segment 5  sequence number: 24002

4) Acknowledgement Number: This is used by the sender to acknowledge the
received data. This 36-bit field indicates the sequence number of the next byte
expected from the receiver. For example, if host A has sent a segment having
sequence number 2000 to host B, host B would send an acknowledgement with
acknowledgement number field set to 2001 (one plus the sequence number of last
received segment).

5) Header Length: The HLEN field consists of 4 bits. It indicates the length of the
TCP header. The length of the TCP header can be between 20 bytes to 60 bytes
i.e., HLEN field can have binary values ranging from 0101-1111 (5 to 15, 32 bit
words) (5 x 4 =20, 15 x 4 =60).

6) Reserved: This 6 bit field is reserved for future use. The value set in this field
must be zero.

7) Control Flags: This field contains six different control flags that can control
certain aspects of the TCP connection such as connection establishment,
connection termination and flow control. The flags include:

a) Urgent Pointer URG: When set, the ACK indicates that the current segment
contains urgent (or high-priority) data and that the Urgent Pointer field value
is valid.

b) Acknowledgement (ACK): When set, indicates that the value contained in
the Acknowledgement Number field is valid. This bit is usually set, except
during the first message during connection establishment.

c) Push (PSH): PSH is used when the transmitting application wants to force
TCP to immediately transmit the data that is currently buffered to the
application without waiting for the buffer to fill. It is useful for transmitting
small units of data.

d) Reset (RST): When set, RST immediately terminates the end-to-end TCP
connection.

e) Synchronize (SYN): SYN is set in the initial segments used to establish a
connection, indicating that the segments carry the initial sequence number.

f) Finish (FIN): FIN is set to request normal termination of the TCP connection
in the direction this segment is travelling. Complete closure of the connection
requires one FIN segment in each direction.

8) Window Size: The window size 16 bits field is used for flow control. It contains
in bytes, the size of the window that the receiver has to maintain i.e., the value of
the receive window size. It is basically the number of transmitted bytes that the
sender of this segment is willing to accept from the receiver.

9) Checksum: This is a 16-bit field that provides bit error detection for the segment
(including the header and data).

10) Urgent Pointer: Urgent data is information that has been marked as high-priority
by a higher layer application. The data sent under high-priority usually bypasses
the normal TCP buffering and is placed in a segment between the header and
normal data. When the URG flag of control flag is set, then the urgent pointer 16-
bit number indicates the position of the first octet of non-priority data in the
segment.

11) Options: The option field contains 40 bytes of optional information about
connection establishment. The maximum segment size (MSS) is the most
commonly used option and if absent, defaults to an MSS of 536. Another option
is Selective Acknowledgement (SACK), which allows out-of-sequence segments
to be accepted by a receiver. The further discussion about options is beyond the
scope of this book.

Characteristics of TCP
The basic characteristics of TCP are as follows:
1) It employs a connection-oriented service for communication.
2) It is a reliable source of communication i.e. guarantees delivery of messages.
3) It splits the messages into segments and keeps track of the order (sequence) of
segments.
4) It employs the checksums for detecting any errors in data as well as the TCP
header.

 The Network Interface layer also called the Network Access layer that handles

placing TCP/IP packets on the network medium and receiving TCP/IP packets off the
network medium. TCP/IP was designed to be independent of the network access
method, frame format, and medium. In this fashion, TCP/IP can be used to connect
differing network types and these include local area network (LAN) media such as
Ethernet and Token Ring and also WAN technologies such as X.25 and Frame Relay.
The network interface layer encompasses the data link and physical layers of the OSI
model.

Internet Layer
The Internet layer handles addressing, packaging, and routing functions. The core
protocols of the Internet layer are IP, ARP, ICMP, and IGMP.

• The Internet Protocol (IP) is a routing protocol that handles IP addressing,
routing, and the fragmentation and reassembly of packets.

• The Address Resolution Protocol (ARP) handles resolution of an Internet layer
address to a Network Interface layer address, such as a hardware address.

• The Internet Control Message Protocol (ICMP) handles providing diagnostic
functions and reporting errors due to the unsuccessful delivery of IP packets.

• The Internet Group Management Protocol (IGMP) handles management of IP
multicast group membership.

The Internet layer is similar to the Network layer of the OSI model.

Transport Layer
The Transport layer handles and provides session and datagram communication
services to Application layer. The core protocols of the Transport layer are
Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP).

• TCP provides a one-to-one, connection-oriented, reliable communications
service. TCP handles the establishment of a TCP connection, the sequencing and
acknowledgment of packets sent, and the recovery of packets lost during
transmission.

• UDP provides a one-to-one or one-to-many, connectionless, unreliable
communications service. UDP is used when the amount of data to be transmitted
is small (such as data that fits into a single packet), when you do not want the
overhead of establishing a TCP connection, or when the applications or upper
layer protocols provide reliable delivery.

The TCP/IP Transport layer is similar to the Transport layer of OSI model.

Application Layer
The application layer provides services for an application program to ensure that
effective communication with another application program in a network is possible.
The application layer is not the application itself that is doing the communication, but
with various application layer protocols.

The most widely known Application layer protocols are those used for the exchange
of user information:

• The Hypertext Transfer Protocol (HTTP) is used to transfer files that make up the
Web pages of the World Wide Web.

• The File Transfer Protocol (FTP) is used for interactive file transfer.

• The Simple Mail Transfer Protocol (SMTP) is used for the transfer of mail
messages and attachments.

• Telnet, a terminal emulation protocol, is used for logging on remotely to network
hosts.

Additionally, the following Application layer protocols help facilitate the use and
management of TCP/IP networks:

• The Domain Name System (DNS) is used to resolve a host name to an IP address.

• The Routing Information Protocol (RIP) is a routing protocol that routers use to
exchange routing information on an IP internetwork.

• The Simple Network Management Protocol (SNMP) is used between a network
management console and network devices (routers, bridges, intelligent hubs) to
collect and exchange network management information.

The TCP/IP Application layer encompasses the responsibilities of the Session,
Presentation, and Application layers of OSI model.