Lab No 1
Lab No 1
Objectives:
Ethernet
Ethernet is the standard way to connect computers on a network over a wired connection. It
provides a simple interface and for connecting multiple devices, such computers, routers,
and switches.
What is an IP address?
“IP address” is a shorter way of saying “Internet Protocol address.” IP addresses are the numbers
assigned to computer network interfaces. Although we use names to refer to the things we seek on
the Internet, such as www.example.org, computers translate these names into numerical addresses
so they can send data to the right location. So when you send an email, visit a web site, or
participate in a video conference, your computer sends data packets to the IP address of the other
end of the connection and receives packets destined for its own IP address.
When computers are connected to Internet they are uniquely identified by an address which is IP
Address.
LAN
Network Devices
Repeater: A repeater is a network device that is used to regenerate or replicate signals that are
weakened or distorted by transmission over long distances and through areas with high levels of
electromagnetic interference (EMI).
Hub: A hub, in the context of networking, is a hardware device that relays communication
data When a packet arrives at one port, it is copied to the other ports so that all segments of the
LAN can see all packets.
Figure 1.3: Hub
Switch:
A switch is a high-speed device that receives incoming data packets and redirects them to their
destination on a local area network (LAN).
Router:
A router is hardware device designed to receive, analyze and move incoming packets to
another network. It may also be used to convert the packets to another network
interface, drop them, and perform other actions relating to a network.
Gateway:
A gateway is a network node that connects two networks using different protocols together. While
a bridge is used to join two similar types of networks, a gateway is used to join two dissimilar
networks. The most common gateway is a router that connects a home or enterprise network to the
internet.
II. Unix Utilities to test Internet connection and to diagnose congestion between
computers:
Ifconfig: The ifconfig command is used to configure a network interface. The following options
are used for the reconfiguration of the IP address and network mask.
ifconfig -a : Shows the states of all interfaces in the system.
ifconfig <interface name> down : Disables the network interface, where interface name is the
name of the Ethernet interface.
ifconfig <interface name> <new IP address> up : Assigns a new IP address to the interface and
brings it up.
ifconfig <interface name > netmask <new netmask> : Assigns a new network mask for the
interface.
Figure 1.8: ifconfig command
Ping: Ping (also written as PING or ping) is a utility that you use to determine whether or not a
specific IP address is accessible. Ping works by sending a packet to a specified address and waiting
for a reply. Ping is used primarily to troubleshoot Internet connections and there are many freeware
and shareware Ping utilities available for download.
$ ping 10.0.0.2
ping 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=128 time=0.457 ms
IV. LAB EXERCISES
1. What is the IP of the machine you are using? Compare it with the IP of your neighbors.
Are the IPs of your neighbors same? Why or Why not?
2. Use the ping command for the following URLs and record the success or failure
statistics along with the average round trip time.
a) google.com
b) facebook.com
3. Based on output of ifconfig /all command, identify the following
Host name[computer name]
MAC address of your system[physical address]
Subnet mask
default gateway
4. In the LAN, compare your result of Q3, with your neighbor computers. What
similarities do you see in the MAC address?
V. ADDITIONAL EXERCISES
1. In the terminal ,type netstat and press enter. The computer displays information
about the open connections on the computer or returns to the prompt if there are
none. Analyze the output.
2. With the help man pages, analyze the results of ping with options.
LAB NO: 2 Date:
Objectives:
To familiarize with application level programming with sockets.
To establish communication between the peers.
To send data through sockets using system calls.
Prerequisites:
I. Introduction
Computer networks has hosts, routers and communication channels. Host computer run
applications, these applications may send and receive data from other host computers through
network. Routers in the network forward information which is in the form of packets. Packets
contain some information such as IP address of sender, receiver and information to be sent.
Protocol is a standard used to define a method of exchanging data over a computer network
such as local area network, Internet, Intranet, etc. Each protocol has its own method of how
data is formatted when sent and what to do with it once received, how that data is compressed
or how to check for errors in data. One of the most common and known protocols is HTTP
(HyperText Transfer Protocol), which is a protocol used to transmit data over the world wide
web (Internet).TCP/IP provides end-to-end connectivity specifying how data should be
formatted, addressed, transmitted, routed, and received at the destination. Each host will be
running multiple applications, PORT NUMBER is used to identify the application running in the host.
Sockets
Sockets allow communication between two different processes on the same or different machines.
To be more precise, it's a way to talk to other computers using standard Unix file descriptors. In
Unix, every I/O action is done by writing or reading a file descriptor. A file descriptor is just an
integer associated with an open file and it can be a network connection, a text file, a terminal, or
something else. To a programmer, a socket looks and behaves much like a low-level file descriptor.
This is because commands such as read() and write() work with sockets in the same way they do
with files and pipes.
Types of Sockets
There are four types of sockets available to the users. The first two are most commonly used and
the last one is rarely used.
Stream Sockets: Delivery in a networked environment is guaranteed. If you send through
the stream socket three items "A, B, C", they will arrive in the same order - "A, B, C".
These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery
is impossible, the sender receives an error indicator. Data records do not have any
boundaries.
Datagram Sockets: Delivery in a networked environment is not guaranteed. They're
connectionless because you don't need to have an open connection as in Stream Sockets -
you build a packet with the destination information and send it out. They use UDP (User
Datagram Protocol).
Raw Sockets: These provide users access to the underlying communication protocols,
which support socket abstractions. Raw sockets are not intended for the general user; they
have been provided mainly for those interested in developing new communication
protocols, or for gaining access to some of the more cryptic facilities of an existing
protocol.
Types of Servers
There are two types of servers you can have:
Iterative Server: This is the simplest form of server where a server process serves one client
and after completing the first request, it takes request from another client. Meanwhile,
another client keeps waiting.
Concurrent Servers: This type of server runs multiple concurrent processes to serve many
requests at a time because one process may take longer and another client cannot wait for
so long. The simplest way to write a concurrent server under Unix is to fork a child process
to handle each client separately.
How to Make a Client
The system calls for establishing a connection are somewhat different for the client and the
server, but both involve the basic construct of a socket. Both the processes establish their
own sockets. The steps involved in establishing a socket on the client side are as follows:
Create a socket with the socket() system call.
Connect the socket to the address of the server using the connect() system call.
Send and receive data. There are a number of ways to do this, but the simplest way is
to use the read() and write() system calls.
Various structures are used in Unix Socket Programming to hold information about the
address and port, and other information. Most socket functions require a pointer to a
socket address structure as an argument. Structures defined in this chapter are related
to Internet Protocol Family.
Socket Descriptor
A simple file descriptor in Unix. Data type is integer.
Socket Address
This construct holds the information for socket address.
syntax
struct sockaddrs {
unsigned short sa_family; // address family, AF_xxx or //PF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
AF stands for Address Family and PF stands for Protocol Family.
Table 2.2 Address Family
Name Purpose
AF_UNIX, AF_LOCAL Local communication
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 sin_family; // Address family unsigned short int sin_port; // Port
number
struct in_addr sin_addr; // Internet address
};
The IP address structure, in_addr, is defined as follows
struct in_addr {
unsigned long int s_addr;
};
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
server_address.sin_addr.s_addr= htonl(INADDR_ANY);
server_address.sin_port = htons(9734);
IP address is a 32bit integer-not convenient for humans. So, the address is written in dotted decimal
representation.
inet_addr() converts the Internet host address from the standard numbers-and-dots
notation into binary data. It returns nonzero if the address is valid, zero if not.
Syntax:
where
Note : The listening socket (sockid) is never used for sending and receiving is used by
the server only as a way to get new sockets.
Syntax:
int newsockid = accept(sockid, &clientAddr, &addrLen);
newsockid is an integer, the new socket is created in server which is client
specific and this new socket is used for data-transfer between server and client.
Sockid is the socket created using socket system call, which is used only to
listen to incoming requests from client.
clientAddr is in the form of struct sockaddr, address of the active participant.
addrLen is size of clientAddrult parameter
Note: accept() is blocking, it waits for connection before returning and dequeues the next
connection on the queue for socket (sockid).
6. Exchanging data with stream socket
Application running in server and client(s) can transfer data using send() and receive()
system call.
Syntax:
int count = send(sockid, msg, msgLen, flags);
Sockid is the new socket descriptor created by accept in server side and socket
in client side, depending on where it is used.
Msg is an array holding message to be transmitted
msgLen holds length of message (in bytes) to transmit
flags are integer, special options, usually set 0
Return value count has number of bytes transmitted and is set to -1 on error
Syntax:
int count = recv(sockid, recvBuf, bufLen, flags);
recvBuf stores received message
bufLen holds number if bytes
7. closing the socket using close()
When finished using a socket, the socket should be closed.
Syntax:
int status= close(sockid);
sockid: the file descriptor (socket being closed)
status: 0 if successful, -1 if error
Closing a socket closes a connection (for stream socket) and frees up the port used by the socket.
Write an iterative TCP client server program where client sends a message to server and server
echoes back the message to client. Client should display the original message and echoed message.
Algorithm: TCPEcho
SERVER:
STEP 1: Start
STEP 6: Listen and accept the client’s request for the connection
CLIENT:
STEP 1: Start
Note: As socket is also a file descriptor, we can use read and write system calls to receive and send
data.
Program:
Server code:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORTNO 10200
int main()
{
int sockfd,newsockfd,portno,clilen,n=1;
char buf[256];
struct sockaddr_in seraddr,cliaddr;
int i,value;
sockfd = socket(AF_INET,SOCK_STREAM,0);
seraddr.sin_family = AF_INET;
seraddr.sin_addr.s_addr = INADDR_ANY;
seraddr.sin_port = htons(PORTNO);
bind(sockfd,(struct sockaddr *)&seraddr,sizeof(seraddr));
listen(sockfd,1);
clilen = sizeof(clilen);
newsockfd=accept(sockfd,(struct sockaddr *)&cliaddr,&clilen);
n = read(newsockfd,buf,sizeof(buf));
printf(" \nMessage from Client %s \n",buf);
n = write(newsockfd,buf,sizeof(buf));
return 0;
}
Client Code:
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int len,result,sockfd,n=1;
struct sockaddr_in address;
char ch[256],buf[256];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family=AF_INET;
address.sin_addr.s_addr=inet_addr("127.0.0.1");
address.sin_port=htons(10200);
len = sizeof(address);
result=connect(sockfd,(struct sockaddr *)&address,len);
if(result==-1)
{
perror("\nCLIENT ERROR");
exit(1);
}
printf("\nENTER STRING\t");
gets(ch);
ch[strlen(ch)]='\0';
write(sockfd,ch,strlen(ch));
printf("STRING SENT BACK FROM SERVER IS .....");
while(n){
n=read(sockfd,buf,sizeof(buf));
puts(buf);
}
return 0;
}
3. First compile and run the server using commands mentioned below
a. $gcc filename –o executablefileName //renaming the a.out file
b. $./ executablefileName
4. Compile and run the client using the same instructions as listed in 3a & 3b.
Note: The ephemeral port number has to be changed every time the program is executed.
1. To illustrate encryption and decryption of messages using TCP. The client accepts message
to be encrypted through standard input device. The client will encrypt the string by adding
4(random value) to ASCII value of each alphabet. The encrypted message is sent to the
server. The server then decrypts the message and displays both encrypted and decrypted
form of the string. Program terminates after one session.
2. Where the client accepts a sentence from the user and sends it to the server. The server will
check for duplicate words in the string. Server will find number of occurrence of duplicate
words present and remove the duplicate words by retaining single occurrence of the word
and send the resultant sentence to the client. The client displays the received data on the
client screen. The process repeats until user enter the string “Stop”. Then both the processes
terminate.