CN Lab Manual-2023-24
CN Lab Manual-2023-24
(U21IT6L2)
III-Year II Semester
LAB MANUAL
Prepared By
Ms. Hajira Sabuhi
Assistant Professor
Ms. Khutaija Abid
Assistant Professor
1
S.NO CONTENTS PAGE NO.
3. PEOs iii
4. POs iv
5. PSOs v
6. COs vi
Programs
2
Institute Vision
Institute Mission
To impart quality professional education that meets the needs of present and emerging
technological world.
To strive for student achievement and success, preparing them for life, career and
leadership.
To provide a scholarly and vibrant learning environment that enables faculty, staff and
students to achieve personal and professional growth.
To contribute to advancement of knowledge, in both fundamental and applied areas of
engineering and technology.
To forge mutually beneficial relationships with government organizations, industries,
society and the alumni.
Department vision
To be a frontier in Information Technology focusing on quality professional education,
innovation and employability.
Department Mission
DM1: Adopt innovative teaching learning processes to achieve stated outcomes and sustained
performance levels.
DM2: Provide learner centric environment to enrich knowledge, skills and innovation through
industry academia collaborations.
DM3: Train the concerned stakeholders on latest technologies to meet the industry needs.
DM4: Inculcate leadership, professional, interpersonal skills and ethical values to address the
contemporary societal issues.
Note: DM: Department Mission
3
Program Educational Objectives (PEOs):
PEO1: Be a competent software engineer in IT and allied industry providing viable solutions.
PEO2: Exhibit professionalism, engage in lifelong learning and adopt to changing industry and
societal needs.
PEO4: Pursue higher studies in Information Technology with emphasis on competency and
innovation.
Program Outcomes
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2: Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences
PO3: Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
4
PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO 12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
PSO1: Professional Skills: Identify, analyze requirements, design and implement computer
programs in the area of artificial intelligence, machine learning, big data analytics and
networking of varying complexity.
PSO2: Problem-Solving Skills: Deliver quality service to IT industry and provide solutions
to real-life problems applying modern computer languages, software methods and tools.
5
Course Outcomes
1. Understand the usage of basic commands ipconig, ifconfig, netstat, ping, arp, telnet, ftp,
finger, trace route, who is of LINUX platform.
2. Develop and Implement Client-Server Socket based programs using TCP, and UDP
sockets.
3. To make a client server communication through TCP and UDP protocols.
4. To expose on advanced socket programming in LINUX environment.
5. Understanding of transport layer protocols : connection oriented and connection-less
models, techniques to provide reliable data delivery.
CO-PO MAPPING
Course Program
Outcomes Specific
Program Outcomes (PO)
(CO) Outcomes
(PSO’s)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO1 PO PSO PSO
1 12 1 2
C367.1 3 3 3 3 3
C367.2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
C367.3 2 2 2 2 2 2 2 2 2 2
C367.4 2 2 2 2 2 2 2 2 2 2 2
C367.5 1 1 1 1 1 1 1 1 1 1
6
Introduction to Socket Programming
Outline:
1.) Introduction
2.) The Client / Server Model
3.) The Socket Interface and Features of a TCP connection 4.) Byte Ordering
5.) Address Structures, Ports, Address conversion functions
6.) Outline of a TCP Server
7.) Outline of a TCP Client
8.) Client-Server communication outline
9.) Summary of Socket Functions
1.) Introduction
In this Lab you will be introduced to socket programming at a very elementary level. Specifically, we will
focus on TCP socket connections which are a fundamental part of socket programming since they provide
a connection oriented service with both flow and congestion control. What this means to the programmer
is that a TCP connection provides a reliable connection over which data can be transferred with little
effort required on the programmers part; TCP takes care of the reliability, flow control, congestion control
for you. First the basic concepts will be discussed, then we will learn how to implement a simple TCP
client and server.
It is possible for two network applications to begin simultaneously, but it is impractical to require it.
Therefore, it makes sense to design communicating network applications to perform complementary
network operations in sequence, rather than simultaneously. The server executes first and waits to receive;
the client executes second and sends the first network packet to the server. After initial contact, either the
client or the server is capable of sending and receiving data.
7
3.) The Socket Interface and Features of a TCP connection
The Internet does not strictly obey the OSI model but rather merges several of the protocols layers
together. Where is the socket programming interface in relation to the protocol stack? Features of a TCP
connection:
8
Features of a TCP connection:
1.Connection Oriented
2. Reliability
i Handles lost packets
ii. Handles packet sequencing
iii. Handles duplicated packets
3. Full Duplex
4. Flow Control
5. Congestion Control
TCP UDP
Connection-oriented Connectionless
Used in applications that require safety gurantee. (eg. Used in media applications. (eg. video or voice
file applications.) transmissions.)
Flow control, sequencing of packets, error-control. No flow or sequence control, user must handle these
manually.
Uses byte stream as unit of transfer. (stream sockets) Uses datagrams as unit of transfer. (datagram sockets)
9
Allows two-way data exchange, once the connection Allows data to be transferred in one direction at once.
is established. (full-duplex) (half-duplex)
e.g. Telnet uses stream sockets. e.g. TFTP (trivial file transfer protocol) uses
Working with sockets is very similar to working with files. The socket() and accept() functions
both return handles (file descriptor) and reads and writes to the sockets requires the use of these
handles (file descriptors).
In Linux, sockets and file descriptors also share the same file descriptor table. That is, if you
open a file and it returns a file descriptor with value say 8, and then immediately open a socket,
you will be given a file descriptor with value 9 to reference that socket. Even though sockets and
files share the same file descriptor table, they are still very different.
Sockets have addresses associated with them whereas files do not, notice that this distinguishes
sockets form pipes, since pipes do not have addresses with which they associate. You cannot
randomly access a socket like you can a file with lseek(). Sockets must be in the correct state to
perform input or output.
Port numbers and IP Addresses (both discussed next) are represented by multi-byte data types
which are placed in packets for the purpose of routing and multiplexing. Port numbers are two
bytes (16 bits) and IP4 addresses are 4 bytes (32 bits), and a problem arises when transferring
multi-byte data types between different architectures.
Say Host A uses a “big-endian” architecture and sends a packet across the network to Host B
which uses a “little-endian” architecture. If Host B looks at the address to see if the packet is for
him/her (choose a gender!), it will interpret the bytes in the opposite order and will wrongly
conclude that it is not his/her packet.
10
The Internet uses big-endian and we call it the network-byte-order, and it is really not important
to know which method it uses since we have the following functions to convert host-byte-
ordered values into network-byte-ordered values and vice versa:
IP4 addresses are 32 bits long. They are expressed commonly in what is known as dotted
decimal notation. Each of the four bytes which makes up the 32 address are expressed as an
integer value (0 – 255) and separated by a dot.
For example, 138.23.44.2 is an example of an IP4 address in dotted decimal notation. There are
conversion functions which convert a 32 bit address into a dotted decimal string and vice versa
which will be discussed later.
Often times though the IP address is represented by a domain name, for example, hill.ucr.edu.
Several functions described later will allow you to convert from one form to another (Magic
provided by DNS!).
The importance of IP addresses follows from the fact that each host on the Internet has a unique
IP address. Thus, although the Internet is made up of many networks of networks with many
different types of architectures and transport mediums, it is the IP address which provides a
cohesive structure so that at least theoretically, (there are routing issues involved as well), any
two hosts on the Internet can communicate with each other.
Ports:
Sockets are UNIQUELY identified by Internet address, end-to-end protocol, and port number.
That is why when a socket is first created it is vital to match it with a valid IP address and a port
number. In our labs we will basically be working with TCP sockets.
Ports are software objects to multiplex data between different applications. When a host receives
a packet, it travels up the protocol stack and finally reaches the application layer. Now consider a
user running an ftp client, a telnet client, and a web browser concurrently. To which application
should the packet be delivered? Well part of the packet contains a value holding a port number,
and it is this number which determines to which application the packet should be delivered.
So when a client first tries to contact a server, which port number should the client specify? For
many common services, standard port numbers are defined.
11
Ports 0 – 1023, are reserved and servers or clients that you create will not be able to bind to
these ports unless you have root privilege.
Ports 1024 – 65535 are available for use by your programs, but beware other network
applications maybe running and using these port numbers as well so do not make assumptions
about the availability of specific port numbers. Make sure you read Stevens for more details
about the available range of port numbers!
Address Structures:
Socket functions like connect(), accept(), and bind() require the use of specifically defined
address structures to hold IP address information, port number, and protocol type. This can be
one of the more confusing aspects of socket programming so it is necessary to clearly understand
how to use the socket address structures. The difficulty is that you can use sockets to program
network applications using different protocols. For example, we can use IP4, IP6, Unix local, etc.
Here is the problem: Each different protocol uses a different address structure to hold its
addressing information, yet they all use the same functions connect(), accept(), bind() etc. So
how do we pass these different structures to a given socket function that requires an address
structure? Well it may not be the way you would think it should be done and this is because
sockets where developed a long time ago before things like a void pointer where features in C.
So this is how it is done:
This is the address structure which must be passed to all of the socket functions requiring an
address structure.
This means that you must type cast your specific protocol dependent address structure to the
generic address structure when passing it to these socket functions.
Protocol specific address structures usually start with sockaddr_ and end with a suffix depending
on that protocol. For example:
12
struct sockaddr_in6 (IP6)
struct sockaddr_un (Unix local)
struct sockaddr_dl (Data link)
So once we fill in this structure with the IP address, port number, etc we will pass this to one of
our socket functions and we will need to type cast it to the generic address structure. For
example:
struct sockaddr_in myAddressStruct;
//Fill in the address information into myAddressStruct here, (will be explained in detail shortly)
For the sa_family variable sin_family always use the constant: PF_INET or AF_INET
***Always initialize address structures with bzero() or memset() before filling them in ***
***Make sure you use the byte ordering functions when necessary for the port and IP address
variables otherwise there will be strange things a happening to your packets.
To convert a string dotted decimal IP4 address to a NETWORK BYTE ORDERED 32 bit value
use the functions:
• inet_addr()
• inet_aton()
To convert a 32 bit NETWORK BYTE ORDERED to a IP4 dotted decimal string use:
• inet_ntoa()
13
Step 1:Creating a socket:
Creating a socket is in some ways similar to opening a file. This function creates a file descriptor
and returns it from the function call. You later use this file descriptor for reading, writing and
using with other socket functions
Parameters:
We need to associate an IP address and port number to our application. A client that wants to
connect to our server needs both of these details in order to connect to our server. Notice the
difference between this function and the connect() function of the client. The connect function
specifies a remote address that the client wants to connect to, while here, the server is specifying to
the bind function a local IP address of one of its Network Interfaces and a local port number.
The parameter socket_file_descriptor is the socket file descriptor returned by a call to socket()
function. The return value of bind() is 0 for success and –1 for failure.
14
**Again make sure that you cast the structure as a generic address structure in this function **
You also do not need to find information about the IP addresses associated with the host you are
working on. You can specify: INNADDR_ANY to the address structure and the bind function will
use on of the available (there may be more than one) IP addresses. This ensures that connections to
a specified port will be directed to this socket, regardless of which Internet address they are sent to.
This is useful if host has multiple IP addresses, then it enables the user to specify which IP address
will be b_nded to which port number.
Binding is like waiting by a specific phone in your house, and Listening is waiting for it to ring.
int listen(int socket_file_descriptor, int backlog);
The backlog parameter can be read in Stevens’ book. It is important in determining how many
connections the server will connect with. Typical values for backlog are 5 – 10.
The parameter socket_file_descriptor is the socket file descriptor returned by a call to socket()
function. The return value of listen() is 0 for success and –1 for failure.
accept() returns a new socket file descriptor for the purpose of reading and writing to the client.
The original file descriptor is used usually used for listening for new incoming connections.
Servers will be discussed in much more detail in a later lab.
It dequeues the next connection request on the queue for this socket of the server. If queue is
empty, this function blocks until a connection request arrives**Again, make sure you type cast to
the generic socket address structure**
Note that the last parameter is a pointer. You are not specifying the length, the kernel is and
returning the value to your application, the same with the ClientAddress. After a connection with a
client is established the address of the client must be made available to your server, otherwise how
could you communicate back with the client? Therefore, the accept() function call fills in the
address structure and length of the address structure for your use. Then accept() returns a new file
descriptor, and it is this file descriptor with which you will read and write to the client.
15
Step 1:Create a socket : Same as in the server.
This is unnecessary for a client, what bind does is (and will be discussed indetail in the server
section) is associate a port number to the application. If you skip this step with a TCP client, a
temporary port number is automatically assigned, so it is just better to skip this step with the client.
Once you have created a socket and have filled in the address structure of the server you want to
connect to, the next thing to do is to connect to that server. This is done with the connect function
listed above.
**This is one of the socket functions which requires an address structure so remember to type cast
it to the generic socket structure when passing it to the second argument **
Connect performs the three-way handshake with the server and returns when the connection is
established or an error occurs.
Once the connection is established you can begin reading and writing to the socket.
16
Communication of 2 pairs via sockets necessitates existence of this 4-tuple:
- Local IP address
- Local Port#
- Foreign IP address
- Foreign Port#
!!!! When a server receives (accepts) the client’s connection request => it forks a copy of itself and lets
the child handle the client. (make sure you remember these Operating Systems concepts)
Therefore on the server machine, listening socket is distinct from the connected socket.
read/write:These are the same functions you use with files but you can use them with sockets as well.
However, it is extremely important you understand how they work so please read Stevens carefully to get a full
understanding.
Writing to a socket:
The return value is the number of bytes written, and –1 for failure. The number of bytes written may be
less than the message_length. What this function does is transfer the data from you application to a buffer
in the kernel on your machine, it does not directly transmit the data over the network. This is extremely
17
important to understand otherwise you will end up with many headaches trying to debug your programs.
TCP is in complete control of sending the data and this is implemented inside the kernel. Due to network
congestion or errors, TCP may not decide to send your data right away, even when the function call
returns. TCP has an elaborate sliding window mechanism which you will learn about in class to control the rate a
which data is sent.
The value returned is the number of bytes read which may not be buffer_length! It returns –1 for failure.
As with write(), read() only transfers data from a buffer in the kernel to your application , you are not
Directly reading the byte stream from the remote host, but rather TCP is in control and buffers the data
for your application.
After you are finished reading and writing to your socket you most call the close system call on the socket
file descriptor just as you do on a normal file descriptor otherwise you waste system resources.
The shutdown() function: You can also shutdown a socket in a partial way which is often used when
Forking off processes. You can shutdown the socket so that it won’t send anymore or you could also
shutdown the socket so that it won’t read anymore as well.
You can look at the man pages for a full description of this function.
• close()
• shutdown()
Client:
• connect()
• bind()
Server:
18
• accept()
• bind()
• listen()
Data Transfer:
• send()
• recv()
• write()
• read()
Miscellaneous:
• bzero()
• memset()
Host Information:
• uname()
• gethostbyname()
• gethostbyaddr()
Address Conversion:
• inet_aton()
• inet_addr()
• inet_ntoa()
19
PROGRAM 1:
Familiarization of Network Environment, Understanding and using network utilities: ipconig,
ifconfig,netstat, ping,arp,telnet, ftp,finger, traceroute,whois.
IFCONFIG
- Viewing Interface Information: Running `ifconfig` without any arguments displays information
about all active network interfaces on the system, including their IP addresses, netmasks, MAC
addresses, transmission and reception statistics, and more.
- Bringing Interfaces Up or Down: `ifconfig` can bring network interfaces up or down. For
instance, you can enable or disable network connectivity for a specific interface using `ifconfig`.
- Diagnostic Tool: It's also used as a diagnostic tool to troubleshoot network connectivity issues
by examining interface configurations and statistics.
Parameters
Parameters used with this command must be prefixed with a hyphen (-) rather than a slash (/).
-a : Displays all active TCP connections and the TCP and UDP ports on which the
computer is listening.
-e : Displays ethernet statistics, such as the number of bytes and packets sent and
received. This parameter can be combined with -s.
-f : Displays fully qualified domain names <FQDN> for foreign addresses.
-i : Displays network interfaces and their statistics (not available under Windows)
-n : Displays active TCP connections, however, addresses and port numbers are expressed
numericallyand no attempt is made to determine names.
-o : Displays active TCP connections and includes the process ID (PID) for each connection.
-p Linux: Process : Show which processes are using which sockets
ab@lab-V520-15IKL:~/Desktop$ ifconfig
OUTPUT
20
inet 172.23.111.206 netmask 255.255.0.0 broadcast 172.23.255.255
inet6 fe80::6210:a84d:878:7702 prefixlen 64 scopeid 0x20<link>
ether 6c:4b:90:49:68:3d txqueuelen 1000 (Ethernet)
RX packets 81034 bytes 88983388 (88.9 MB)
RX errors 0 dropped 69 overruns 0 frame 0
TX packets 40659 bytes 6950281 (6.9 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
EXPLANATION
Sure, let's break down each line from the network interface configuration:
1. `flags=4163<UP,BROADCAST,RUNNING,MULTICAST>`:
- `UP`: Indicates that the interface is up and operational.
- `BROADCAST`: Indicates that the interface supports broadcast transmissions.
- `RUNNING`: Indicates that the interface is operational.
- `MULTICAST`: Indicates that the interface supports multicast transmissions.
2. `mtu 1500`:
- `mtu`: Stands for Maximum Transmission Unit, which is the maximum size of a data packet
that can be transmitted over the network. In this case, it's set to 1500 bytes.
21
5. `ether 6c:4b:90:49:68:3d txqueuelen 1000 (Ethernet)`:
- `ether`: Indicates the hardware (MAC) address of the interface. Here, it's `6c:4b:90:49:68:3d`.
- `txqueuelen`: Stands for Transmit Queue Length. It represents the length of the transmit
queue for this interface. In this case, it's `1000`.
- `(Ethernet)`: Indicates the type of interface, which is Ethernet.
The netmask, short for network mask, is a 32-bit number that is used to divide an IP address into
network and host portions. It is used in conjunction with an IP address to determine the network
to which the address belongs.
NETSTAT
- Viewing Network Connections: `netstat` can display a list of all network connections, both
incoming and outgoing, along with their associated protocol, local and remote addresses, and
state.
- Displaying Routing Table: It can also show the routing table of the system, including
information about the network interfaces and their associated routes.
- Monitoring Network Statistics: `netstat` can be used to monitor various network statistics, such
as the number of packets and bytes transmitted and received, error counts, and more.
22
- Displaying Multicast Memberships: `netstat` can display information about multicast group
memberships for IPv4 and IPv6.
- Displaying Network Services: With appropriate options, `netstat` can show information about
network services and their associated ports.
lab@lab-V520-15IKL:~/Desktop$ netstat
Each line in the provided output represents a Unix domain socket or communication endpoint.
Here's an explanation of each field and what it represents:
23
- Indicates a connected stream Unix domain socket associated with the AT-SPI accessibility
bus for a specific user (`999`).
PING
24
`ping` is a command-line utility used to test the reachability of a host on an Internet Protocol (IP)
network and to measure the round-trip time for messages sent from the originating host to a
destination computer. Here's a brief overview of its functionality:
- Basic Functionality: `ping` sends ICMP (Internet Control Message Protocol) Echo Request
messages to the target host and waits for ICMP Echo Reply messages in response.
- Reachability Test: It verifies whether the target host is reachable over the network. If the host
responds to the ICMP Echo Request, it means the host is reachable.
- Round-Trip Time (RTT) Measurement: `ping` measures the round-trip time taken for an ICMP
Echo Request message to travel from the source to the destination and back. This RTT provides
an indication of the network latency between the source and destination.
- Continuous Testing: By default, `ping` sends a single ICMP Echo Request and waits for a reply.
However, it can also be configured to send a continuous stream of ICMP Echo Request
messages, allowing users to monitor the connectivity status over time.
- Packet Loss Detection: `ping` detects packet loss by analyzing the percentage of ICMP Echo
Request messages that do not receive a corresponding ICMP Echo Reply. Packet loss can
indicate network congestion or connectivity issues.
- IPv4 and IPv6 Support: `ping` supports both IPv4 and IPv6 addresses, enabling testing across
different network protocols.
`ping` is a simple yet powerful tool for network troubleshooting, diagnosing connectivity issues,
and measuring network performance.
25
--- www.google.com ping statistics ---
124 packets transmitted, 124 received, 0% packet loss, time 123174ms
rtt min/avg/max/mdev = 18.124/18.472/23.772/0.842 ms
EXPLANATION
Each line in the provided output of the ping command represents a response from the destination
host (www.google.com), along with some additional information.
3. The subsequent lines follow the same format as line 2, each representing a response to an
ICMP Echo Request message sent.
26
ARP
ARP (Address Resolution Protocol) is a protocol used for mapping an IP address to a physical
machine address, such as an Ethernet MAC address. Here's a brief overview:
- Protocol Operation: When a device needs to send data to another device within its network, it
checks its ARP cache (a table of recent IP-to-MAC mappings). If the mapping isn't found, it
sends out an ARP request broadcast asking for the MAC address associated with the target IP.
- Response: The device with the corresponding IP address responds with its MAC address,
allowing the requesting device to update its ARP cache and establish communication.
- Address Resolution: ARP is crucial for Ethernet networks, where MAC addresses are used for
low-level communication. It helps devices locate each other on the same network segment.
-Dynamic Nature: ARP mappings are dynamic and can change over time due to network changes
or device configurations.
- ARP Cache: Devices maintain an ARP cache to store recently resolved mappings, improving
efficiency by reducing the need for repeated ARP requests.
lab@lab-V520-15IKL:~/Desktop$ arp
EXPLANATION
Each line of the output represents an entry in the ARP cache table. Here's an explanation of each
field:
27
- `44:37:e6:e4:65:26`: The MAC address corresponding to the IP address.
- `C`: Indicates that this is a complete (resolved) entry in the ARP cache.
- `enp1s0`: The network interface associated with this ARP entry.
- Gateway: A network node or device serving as an entry point into another network, facilitating
communication between different networks.
- Default Gateway: Specifically in TCP/IP networking, the router or network device used to
forward traffic from a device to destinations outside its local network or subnet. It's the default
route for traffic not matching any other specific route in the device's routing table.
TELNET
Telnet is a network protocol used on the Internet or local area networks to provide bidirectional
interactive text-oriented communication between two devices. It allows a user to remotely access
and manage another computer or device over a network, typically using a command-line
interface.
1. Connection Establishment: The Telnet client initiates a connection to the Telnet server by
specifying the server's IP address or domain name and the port number (usually port 23).
2. Session Initiation: Once the connection is established, a Telnet session begins, allowing the
user to interact with the remote system. This interaction typically takes place through a text-
based terminal interface.
3. Text Transmission: Commands and responses are exchanged between the client and server as
plain text. The user sends commands to the remote system, which executes them and sends back
the results.
4. End of Session: When the user finishes the session, they can gracefully terminate the
connection, closing the Telnet session.
While Telnet is a simple and straightforward protocol, it's important to note that it lacks security
features. Communications through Telnet are not encrypted, meaning that sensitive information,
such as login credentials, can be intercepted by malicious actors if transmitted over insecure
networks. As a result, Telnet has largely been replaced by more secure protocols like SSH
(Secure Shell) for remote access and management tasks.
Protocol details:
Telnet is a client-server protocol, based on a reliable connection-oriented transport.
Typically this protocol is used to establish a connection to TCP port 23.
sudo apt install telnetd-y(install in both systems)
28
telnet <ip address>
ex: telnet 172.23.101.141...
connected to 172.23.101.141
login :student
pwd: lords
welcome to Ubuntu
ls:
Desktop Documents Downloads....
cd Desktop
All files will be displayed
FTP
FTP, or File Transfer Protocol, is a standard network protocol used for transferring files from one
host to another over a TCP-based network, such as the Internet or a local network. Here's a brief
overview:
1. Client-Server Architecture: FTP operates on a client-server model, where one device (the
client) initiates a connection to another device (the server) to transfer files.
2. Two Connection Channels: FTP uses two separate channels for communication: the control
channel and the data channel. The control channel handles commands and responses between the
client and server, while the data channel is used for transferring actual file data.
3. Commands and Responses: FTP clients send commands to the FTP server to perform various
operations such as listing directories, uploading files, downloading files, renaming files, and
deleting files. The server responds to these commands with status codes to indicate the success or
failure of the operation.
4. Modes of Operation: FTP supports two modes of operation: active mode and passive mode. In
active mode, the client initiates the data connection to the server, while in passive mode, the
server initiates the data connection to the client. Passive mode is commonly used when the client
is behind a firewall or NAT device.
5. Security Considerations: Traditional FTP transmits data, including usernames and passwords,
in plain text, making it susceptible to eavesdropping attacks. To address this issue, secure
alternatives like FTPS (FTP Secure) and SFTP (SSH File Transfer Protocol) have been
developed, which add encryption and authentication mechanisms to FTP.
29
Overall, FTP is a widely used protocol for transferring files between systems, although its use
has declined in favor of more secure alternatives like FTPS and SFTP, as well as web-based file
transfer solutions.
.
.
.
TRANSFER COMPLETE
FTP> LS
SHOWS ALL FILES
FTP>?
FINGER
The `finger` command is a simple utility used in Unix-like operating systems to retrieve
information about users on a remote system. It allows users to gather details such as login name,
real name, terminal name, idle time, login time, and more. Here's a brief overview:
1. Usage: To use the `finger` command, simply type `finger` followed by the username you want
to query. For example:
```
30
finger username
```
2. Information Provided: When you execute the `finger` command with a username, it typically
returns information about that user, including their login name, real name, terminal name, login
time, idle time, and possibly other details depending on the system configuration.
3. System Configuration: The information displayed by the `finger` command can vary based on
the system's configuration. System administrators can control the type and amount of
information that the `finger` command displays.
4. Security Concerns: `finger` can reveal sensitive information about users on a system, so its use
may be restricted or disabled on some systems for security reasons.
5. Alternative Usage: In addition to querying specific usernames, you can also use `finger`
without specifying a username to display a list of users currently logged into the system.
Overall, the `finger` command provides a convenient way to retrieve basic information about
users on a Unix-like system, but its use may be limited due to security considerations.
31
1. Login: This column shows the username or login name of the user currently logged in.
2. Name: This column typically displays the real name associated with the user account.
However, in many cases, it may display a generic label like "Guest" or "Lab" instead of an actual
name.
3. Tty: This column indicates the terminal (or TTY - TeleTYpewriter) to which the user is logged
in. Each terminal session on a Unix-like system is assigned a unique TTY number.
4. Idle: This column shows the idle time of the user, indicating how long the user's terminal
session has been inactive. In the provided example, "3:03" suggests that the user's terminal has
been idle for three hours and three minutes.
5. Login Time: This column displays the time when the user logged into the system. In the
provided example, it shows the date and time of the login, such as "Mar 11 10:31" for March
11th at 10:31 AM.
6. Office: This column typically provides additional information about the user, such as their job
title, department, or location. In the example, it seems to display the name of the office
associated with the user's session, like "415-lab" for laboratory 415.
7. Office Phone: This column, if available, would display the phone number associated with the
user's office or workplace. However, in the provided example, it appears to be empty.
TRACEROUTE
Traceroute is a network diagnostic tool used to trace the route that packets take from one host to
another across an IP network. It works by sending packets with gradually increasing time-to-live
(TTL) values to the destination host and analyzing the ICMP (Internet Control Message
Protocol) error messages returned by intermediate routers.
Here's a brief overview of how traceroute works:
1. Packet Transmission: Traceroute sends packets to the destination host with an initial TTL
value of 1. When the packet reaches the first router, the TTL expires, and the router sends back
an ICMP Time Exceeded message to the sender.
2. Hop-by-Hop Analysis: Traceroute then sends another packet with a TTL value of 2, causing it
to reach the second router along the path before expiring. This process repeats, gradually
increasing the TTL value with each packet sent, until the packet reaches the destination host.
3. Recording Route Information: As the packets traverse the network, each router along the path
forwards the packet to the next hop and responds with an ICMP Time Exceeded message.
Traceroute records the IP address and round-trip time (RTT) of each router in the path.
4. Displaying Results: Traceroute displays the recorded information, showing the sequence of
routers (often referred to as hops) that packets took to reach the destination host. It also provides
the RTT for each hop, indicating the time taken for the packet to travel to that router and back.
32
5. Identifying Network Issues: Traceroute is commonly used to diagnose network connectivity
issues, such as routing misconfigurations, packet loss, or network congestion. By analyzing the
traceroute results, network administrators can identify problematic routers or network segments
causing delays or disruptions.
Overall, traceroute is a valuable tool for troubleshooting network problems and understanding
the path that packets take across the Internet or local network. It provides insights into the
network topology and helps pinpoint the source of connectivity issues.
INSTALL
lab@lab-V520-15IKL:~/Desktop$ sudo apt install inetutils-traceroute
traceroute google.com
traceroute to google.com (142.250.76.174), 64 hops max
1 172.23.100.1 0.413ms 0.310ms 0.240ms
2 103.102.86.145 8.458ms 2.159ms 2.155ms
3 103.88.102.1 1.160ms 1.046ms 0.934ms
4 103.41.98.33 1.439ms 1.469ms 1.575ms
5 * * *
6 * * *
7 198.18.5.19 20.890ms 20.785ms 20.777ms
8 72.14.198.36 17.894ms 17.862ms 17.921ms
9 192.178.110.123 26.066ms 25.811ms 25.861ms
10 74.125.253.165 18.513ms 18.446ms 18.446ms
11 142.250.209.70 16.313ms 16.652ms 16.116ms
12 192.178.110.107 21.126ms 21.303ms 21.315ms
13 142.250.76.174 20.851ms 27.201ms 21.287ms
EXPLANATION
`1 172.23.100.1 0.413ms 0.310ms 0.240ms`: This line indicates the first hop in the traceroute
path.
- `1`: Represents the hop count, indicating that this is the first router encountered.
33
- `172.23.100.1`: IP address of the first router.
- `0.413ms`, `0.310ms`, `0.240ms`: Round-trip time (RTT) in milliseconds for three packets
sent to the first router.
`2 103.102.86.145 8.458ms 2.159ms 2.155ms`: This line represents the second hop in the
traceroute path.
- `2`: Indicates the second hop.
- `103.102.86.145`: IP address of the second router.
- `8.458ms`, `2.159ms`, `2.155ms`: RTT for three packets sent to the second router.
`3 103.88.102.1 1.160ms 1.046ms 0.934ms`: This line represents the third hop.
- `3`: Third hop in the path.
- `103.88.102.1`: IP address of the third router.
- `1.160ms`, `1.046ms`, `0.934ms`: RTT for three packets sent to the third router.
`4 103.41.98.33 1.439ms 1.469ms 1.575ms`: This line represents the fourth hop.
- `4`: Fourth hop in the path.
- `103.41.98.33`: IP address of the fourth router.
- `1.439ms`, `1.469ms`, `1.575ms`: RTT for three packets sent to the fourth router.
`5 * * *`: This line indicates that the traceroute tool didn't receive a response from the fifth
hop. The asterisks (*) represent lost packets or no response within the timeout period.
`6 * * *`: Similar to the previous line, traceroute didn't receive a response from the sixth hop.
`7 198.18.5.19 20.890ms 20.785ms 20.777ms`: This line represents the seventh hop.
- `7`: Seventh hop in the path.
- `198.18.5.19`: IP address of the seventh router.
- `20.890ms`, `20.785ms`, `20.777ms`: RTT for three packets sent to the seventh router.
`8 72.14.198.36 17.894ms 17.862ms 17.921ms`: This line represents the eighth hop.
34
- `8`: Eighth hop in the path.
- `72.14.198.36`: IP address of the eighth router.
- `17.894ms`, `17.862ms`, `17.921ms`: RTT for three packets sent to the eighth router.
`9 192.178.110.123 26.066ms 25.811ms 25.861ms`: This line represents the ninth hop.
- `9`: Ninth hop in the path.
- `192.178.110.123`: IP address of the ninth router.
- `26.066ms`, `25.811ms`, `25.861ms`: RTT for three packets sent to the ninth router.
`10 74.125.253.165 18.513ms 18.446ms 18.446ms`: This line represents the tenth hop.
- `10`: Tenth hop in the path.
- `74.125.253.165`: IP address of the tenth router.
- `18.513ms`, `18.446ms`, `18.446ms`: RTT for three packets sent to the tenth router.
`11 142.250.209.70 16.313ms 16.652ms 16.116ms`: This line represents the eleventh hop.
- `11`: Eleventh hop in the path.
- `142.250.209.70`: IP address of the eleventh router.
- `16.313ms`, `16.652ms`, `16.116ms`: RTT for three packets sent to the eleventh router.
`12 192.178.110.107 21.126ms 21.303ms 21.315ms`: This line represents the twelfth hop.
- `12`: Twelfth hop in the path.
- `192.178.110.107`: IP address of the twelfth router.
- `21.126ms`, `21.303ms`, `21.315ms`: RTT for three packets sent to the twelfth router.
`13 142.250.76.174 20.851ms 27.201ms 21.287ms`: This line represents the final destination.
- `13`: Indicates the final destination.
- `142.250.76.174`: IP address of the destination host (in this case, google.com).
- `20.851ms`, `27.201ms`, `21.287ms`: RTT for three packets sent to the destination host.
35
PROGRAM-2:
Write a program to implement connection oriented and connection less client for well-
known services i.e., standard ports.
connection oriented
//Server
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(sockfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
36
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
25
}
else
printf("server acccept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}
SAVE: conn-oriented-server.c
37
COMPILE: gcc conn-oriented-server.c
RUN:./a.out
CLIENT.C
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
38
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
SAVE: conn-oriented-server.c
COMPILE: gcc conn-oriented-server.c
RUN:./a.out
Connection Less
//SERVER
#include <stdio.h>
#include <errno.h>
#include <netinet/in.h>
39
#define DATA_BUFFER 5000
int main ()
{
struct sockaddr_in saddr, new_addr;
int fd, ret_val;
char buf[DATA_BUFFER];
socklen_t addrlen;
/* Step1: open a UDP socket */
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd == -1) {
fprintf(stderr, "socket failed [%s]\n", strerror(errno));
return -1;
}
printf("Created a socket with fd: %d\n", fd);
/* Initialize the socket address structure */
saddr.sin_family = AF_INET;
saddr.sin_port = htons(7000);
saddr.sin_addr.s_addr = INADDR_ANY;
/* Step2: bind the socket */
ret_val = bind(fd, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in));
if (ret_val != 0) {
fprintf(stderr, "bind failed [%s]\n", strerror(errno));
close(fd);
return -1;
}
/* Step3: Start receiving data. */
printf("Let us wait for a remote client to send some data\n");
ret_val = recvfrom(fd, buf, DATA_BUFFER, 0,
40
(struct sockaddr *)&new_addr, &addrlen);
if (ret_val != -1) {
printf("Received data (len %d bytes): %s\n", ret_val, buf);
} else {
printf("recvfrom() failed [%s]\n", strerror(errno));
}
/* Last step: close the socket */
close(fd);
return 0;
}
SAVE: conn-less-server.c
COMPILE: gcc conn-less-server.c
RUN:./a.out
OUTPUT:
//Client
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#define DATA_BUFFER "Mona Lisa was painted by Leonardo da Vinci"
int main () {
41
struct sockaddr_in saddr;
int fd, ret_val;
struct hostent *host; /* need netdb.h for this */
/* Step1: open a UDP socket */
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd == -1) {
fprintf(stderr, "socket failed [%s]\n", strerror(errno));
return -1;
}
printf("Created a socket with fd: %d\n", fd);
/* Next, initialize the server address */
saddr.sin_family = AF_INET;
saddr.sin_port = htons(7000);
host = gethostbyname("127.0.0.1");
saddr.sin_addr = *((struct in_addr *)host->h_addr);
/* Step2: send some data */
ret_val = sendto(fd,DATA_BUFFER, strlen(DATA_BUFFER) + 1, 0,
(struct sockaddr *)&saddr, sizeof(struct sockaddr_in));
if (ret_val != -1) {
printf("Successfully sent data (len %d bytes): %s\n", ret_val, DATA_BUFFER);
} else {
printf("sendto() failed [%s]\n", strerror(errno));
}
/* Last step: close the socket */
close(fd);
return 0;
}
SAVE: conn-less-client.c
COMPILE: gcc conn-less-client.c
42
RUN:./a.out
OUTPUT:
43
PROGRAM 3:
Implementation of concurrent server service using connection-oriented socket system
calls(Service: Daytime)
A concurrent server service using connection-oriented socket system calls, specifically for the Daytime
service, involves creating a server that can handle multiple client connections simultaneously, providing
each client with the current date and time upon request.
1. Socket Initialization: The server initializes a socket using the `socket()` system call. This socket will be
used to listen for incoming connections from clients.
2. Binding: The server binds the socket to a specific port using the `bind()` system call. This allows
clients to connect to the server using the specified port number.
3. Listening: The server sets the socket to listen for incoming connections using the `listen()` system call.
This prepares the socket to accept client connections.
4. Accepting Connections: The server enters a loop where it continuously accepts incoming connections
using the `accept()` system call. Each time a client connects, the server creates a new socket dedicated to
handling communication with that client.
5. Handling Clients Concurrently: For each accepted connection, the server forks a new process or
spawns a new thread to handle communication with the client concurrently. This allows the server to
handle multiple clients simultaneously without blocking.
6. Daytime Service: Upon receiving a connection from a client, the server retrieves the current date and
time using system-specific functions (e.g., `gettimeofday()` or `localtime()`) and sends this information
back to the client over the established connection.
7. Closing Connections: After sending the date and time to the client, the server closes the connection for
that client using the `close()` system call. The server then continues to listen for new connections.
8. Shutdown: When the server needs to stop, it closes the listening socket and terminates any remaining
client connections gracefully.
44
Here are the methods involved in implementing a concurrent server service for the Daytime protocol
using connection-oriented socket system calls:
1. initialize_socket(): This method initializes the socket for communication. It calls the `socket()` system
call to create a new socket and sets it up for TCP communication.
2. bind_socket(): This method binds the socket to a specific IP address and port number using the `bind()`
system call. It specifies the address and port on which the server will listen for incoming connections.
3. listen_for_connections(): This method sets the socket to the listening state using the `listen()` system
call. It specifies the maximum number of pending connections that can be queued up by the operating
system.
4. accept_connections(): This method continuously accepts incoming connections using the `accept()`
system call within a loop. When a new connection is accepted, it spawns a new process or thread to
handle communication with the client.
5. handle_client(): This method is called for each accepted connection to handle communication with the
client. It retrieves the current date and time using system-specific functions and sends this information
back to the client over the established connection.
6. close_connection(): This method closes the connection with the client using the `close()` system call
after sending the date and time information. It ensures that the resources associated with the connection
are released properly.
7. shutdown_server(): This method shuts down the server gracefully. It closes the listening socket and
terminates any remaining client connections before exiting the server application.
//Client Program
#include"netinet/in.h"
#include"sys/socket.h"
#include"stdio.h"
45
main()
{
struct sockaddr_in sa,cli;
int n,sockfd;
int len;char buff[100];
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){ printf("\nError in Socket");
exit(0);
}
else printf("\nSocket is Opened");
bzero(&sa,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_port=htons(5600);
if(connect(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("\nError in connection failed");
exit(0);
}
else
printf("\nconnected successfully");
if(n=read(sockfd,buff,sizeof(buff))<0)
{
printf("\nError in Reading");
exit(0);
}
else
{printf("\nMessage Read %s",buff);
}}
SAVE: concurrent-client.c
46
COMPILE: gcc concurrent-client.c
RUN:./a.out
OUTPUT:
SAVE: concurrent-client.c
COMPILE: gcc concurrent-client.c
RUN:./a.out
OUTPUT:
//Server Program
#include"netinet/in.h"
#include"sys/socket.h"
#include"stdio.h"
#include"string.h"
#include"time.h"
main( )
{
struct sockaddr_in sa;
struct sockaddr_in cli;int sockfd,conntfd;int len,ch;char str[100];
time_t tick;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
printf("error in socket\n");
47
exit(0);
}
else printf("Socket opened");
bzero(&sa,sizeof(sa));
sa.sin_port=htons(5600);
sa.sin_addr.s_addr=htonl(0);
if(bind(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("Error in binding\n");
}
else
printf("Binded Successfully");
listen(sockfd,50);
for(;;)
{
len=sizeof(ch);
conntfd=accept(sockfd,(struct sockaddr*)&cli,&len);
printf("Accepted");
tick=time(NULL);
snprintf(str,sizeof(str),"%s",ctime(&tick));
printf("%s",str);write(conntfd,str,100);
}
}
SAVE: concurrent-server.c
COMPILE: gcc concurrent-server.c
RUN: ./a.out
OUTPUT:
48
PROGRAM 4:
Implementation of concurrent server using connection less socket system calls.(Service:
Echo server)
SERVER PROGRAM
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd, rval, pid;
char buff1[20], buff2[20];
struct sockaddr_in server, client;
int len;
sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd == -1)
{
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(3221);
rval = bind(sockfd, (struct sockaddr *)&server, sizeof(server));
if (rval != -1)
{
pid = fork();
if (pid == 0)
{
printf("\n Childprocess Executing \n");
49
printf("\n child process ID Is:%d\n",
getpid());
len = sizeof(client);
rval = recvfrom(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr *)&client, &len);
if (rval == -1)
{
perror("\n RECV_ERR\n");
exit(1);
}
else
{
printf("\n Received Message Is:%s\n", buff1);
}
rval = sendto(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr *)&client, sizeof(client));
if (rval != -1)
{
printf("\n Message sent successfully \n");
}
else
{
perror("\n SEND_ERR\n");
exit(1);
}
}
else
printf("\n parent process\n");
printf("parent process ID is %d\n", getppid());
}
else
{
50
perror("\n BIND_ERR\n");
exit(1);
}
}
CLIENT PROGRAM
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd, rval;
char buff1[20], buff2[20];
struct sockaddr_in server, client;
int len;
sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd == -1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(3221);
printf("\n enter a message \n");
scanf("%s", buff1);
51
rval = sendto(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr *)&server, sizeof(server));
if (rval != -1)
{
printf("\nmessage sent successfully\n");
}
else
{
perror("\n SEND_ERR\n");
exit(1);
}
len = sizeof(server);
rval = recvfrom(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr *)&server, &len);
if (rval == -1)
{
perror("\nRECV_ERR\n");
exit(1);
}
else
{
printf("\n Received Message is %s\n", buff1);
}
}
52
OUTPUT:
screenshot 1:
screenshot 2:
53
PROGRAM 5:
Write a programs for TCP chat server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include<errno.h>
int main() {
int server_fd, client_fds[MAX_CLIENTS], max_sd, activity, sd, new_socket;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
fd_set readfds;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
if (listen(server_fd, 5) == -1) {
54
perror("listen");
exit(EXIT_FAILURE);
}
while (1) {
FD_ZERO(&readfds);
FD_SET(server_fd, &readfds);
max_sd = server_fd;
if (FD_ISSET(server_fd, &readfds)) {
if ((new_socket = accept(server_fd, NULL, NULL)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
55
if (client_fds[i] == 0) {
client_fds[i] = new_socket;
break;
}
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
56
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
int sockfd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
while (1) {
printf("Enter message: ");
fgets(buffer, BUFFER_SIZE, stdin);
send(sockfd, buffer, strlen(buffer), 0);
}
close(sockfd);
return 0;
}
57
PROGRAM 6:
Write a programs for UDP chat server.
Theory In UDP, the client does not form a connection with the server like in TCP and instead
just sends a datagram. Similarly, the server need not accept a connection and just waits for
datagrams to arrive. Datagrams upon arrival contain the address of sender which the server uses
to send data to the correct client.
The entire process can be broken down into following steps : UDP Server :
1. Create UDP socket.
2. Bind the socket to server address.
3. Wait until datagram packet arrives from client.
4. Process the datagram packet and send a reply to client.
5. Go back to Step 3.
UDP Client :
1. Create UDP socket.
2. Send message to server.
3. Wait until response from server is recieved.
4. Process reply and go back to step 2, if necessary.
5. Close socket descriptor and exit.
Necessary Functions :
int socket(int domain, int type, int protocol)
58
Creates an unbound socket in the specified domain.
Returns socket file descriptor.
Arguments : domain – Specifies the communication domain ( AF_INET for IPv4/ AF_INET6 for IPv6 )
type – Type of socket to be created ( SOCK_STREAM for TCP / SOCK_DGRAM for UDP ) protocol –
Protocol to be used by socket. 0 means use default protocol for the address family.
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
Assigns address to the unbound socket.
Arguments : sockfd – File descriptor of socket to be binded addr – Structure in which address to be
binded to is specified addrlen – Size of addr structure
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen)
Send a message on the socket
Arguments : sockfd – File descriptor of socket buf – Application buffer containing the data to
be sent len – Size of buf application buffer flags – Bitwise OR of flags to modify socket
behaviour dest_addr – Structure containing address of destination addrlen – Size of dest_addr
structure.
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen)
Receive a message from the socket.
Arguments : sockfd – File descriptor of socket buf – Application buffer in which to receive data len –
Size of buf application buffer flags – Bitwise OR of flags to modify socket behaviour src_addr –
Structure containing source address is returned addrlen – Variable in which size of src_addr structure is
returned
int close(int fd)
Close a file descriptor
Arguments : fd – File descriptor
In the below code, exchange of one hello message between server and client is shown to demonstrate the
model.
// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
59
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Hello message sent.\n");
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *) &servaddr,
&len);
buffer[n] = '\0';
60
printf("Server : %s\n", buffer);
close(sockfd);
return 0;
}
Output :
$ ./server
Client : Hello from client
Hello message sent.
$ ./client
Hello message sent.
61
PROGRAM 7:
Program to demonstrate the use of advanced socket system
calls:readv(),writev(),getsockname(),setsockname(),getpeername(),gethostbyname(),gethost
byaddr(),getnetbyname(),getnetbyaddr(),getprotobyname(),getserv
1. WRITE()
#include<unistd.h>
int main()
{
write(1,"hello\n",6); //1 is the file descriptor, "hello\n" is the data, 6 is the count of characters in data
}
OUTPUT
hello
2. READV()
#include<unistd.h>
int main()
{
char buff[20];
read(0,buff,10);//read 10 bytes from standard input device(keyboard), store in buffer (buff)
write(1,buff,10);//print 10 bytes from the buffer on the screen
}
62
OUTPUT
1234567
3. getsockname()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
char myIP[16];
unsigned int myPort;
struct sockaddr_in server_addr, my_addr;
int sockfd;
// Connect to server
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Can't open stream socket.");
exit(-1);
}
// Set server_addr
63
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
server_addr.sin_port = htons(SERVER_PORT);
// Connect to server
if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
perror("Connect server error");
close(sockfd);
exit(-1);
}
return 0;
}
OUTPUT
64
Local ip address: 178.77.101.235
Local port : 38576
4. Setsockname()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main() {
int sockfd;
struct sockaddr_in addr;
// Create socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
65
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("Bind failed");
exit(EXIT_FAILURE);
}
return 0;
}
OUTPUT
66
5. gethostbyname()
67
}
}
// Driver code
int main()
{
char hostbuffer[256];
char *IPbuffer;
struct hostent *host_entry;
int hostname;
// To retrieve hostname
hostname = gethostname(hostbuffer, sizeof(hostbuffer));
checkHostName(hostname);
68
// To convert an Internet network
// address into ASCII string
IPbuffer = inet_ntoa(*((struct in_addr*)
host_entry->h_addr_list[0]));
return 0;
}
OUTPUT
Hostname: lvps178-77-101-235.dedicated.hosteurope.de
Host IP: 178.77.101.235
6. getpeername()
server program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
69
#define PORT 8080
int main() {
int sockfd, new_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(client_addr);
70
printf("Server listening on port %d...\n", PORT);
close(sockfd);
return 0;
}
Client program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
71
#define PORT 8080
int main() {
int sockfd, new_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(client_addr);
72
printf("Server listening on port %d...\n", PORT);
close(sockfd);
return 0;
}
COMPILE:
gcc server.c -o server
gcc client.c -o client
RUN:
./server
./client
73
Connected to server on port 8080
7. gethostbyaddress()
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
int main() {
struct hostent *host_entry;
struct in_addr addr;
char ip_address[INET_ADDRSTRLEN];
// IP address to resolve
const char *ip = "8.8.8.8";
74
}
return 0;
}
OUTPUT:
8. gethostbyname()
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
int main() {
struct hostent *host_entry;
75
const char *domain = "example.com";
return 0;
}
OUTPUT
9. getnetbyname()
#include <stdio.h>
76
#include <stdlib.h>
#include <netdb.h>
int main() {
struct netent *net_entry;
return 0;
}
OUTPUT:
getnetbyname: Success
77
10. getnetbyaddr()
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
int main() {
struct netent *net_entry;
unsigned long net_number;
78
return 0;
}
OUTPUT:
getnetbyaddr: Success
11. getprotobyname()
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
int main() {
struct protoent *proto_entry;
79
// Display protocol information
printf("Protocol name: %s\n", proto_entry->p_name);
printf("Protocol number: %d\n", proto_entry->p_proto);
return 0;
}
OUTPUT:
12. gerserverbyname()
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
int main() {
struct servent *serv_entry;
80
if (serv_entry == NULL) {
perror("getservbyname");
exit(EXIT_FAILURE);
}
return 0;
}
OUTPUT:
81
Viva Questions
82
83