0% found this document useful (0 votes)
10 views55 pages

Network Programming Concepts Explained

The document provides an overview of network programming concepts, covering definitions of web-related terms, features of Unix, server roles, socket operations, and differences between TCP and UDP. It explains I/O multiplexing, various I/O models, and essential socket system calls for both connection-oriented (TCP) and connectionless (UDP) communication. Additionally, it discusses the select and poll functions for managing multiple connections and outlines the OSI Reference Model.

Uploaded by

Deepanshu P
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views55 pages

Network Programming Concepts Explained

The document provides an overview of network programming concepts, covering definitions of web-related terms, features of Unix, server roles, socket operations, and differences between TCP and UDP. It explains I/O multiplexing, various I/O models, and essential socket system calls for both connection-oriented (TCP) and connectionless (UDP) communication. Additionally, it discusses the select and poll functions for managing multiple connections and outlines the OSI Reference Model.

Uploaded by

Deepanshu P
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NETWORK PROGRAMMING

SECTION A — SHORT NOTES ANSWERS

1. Define Web Page, Web Site and Web Browser?

●​ Web Page: A document written in HTML that is displayed in a web browser. It


may contain text, images, links, audio, video etc.
●​ Web Site: A collection of related web pages located under a single domain
name, stored on a web server.
●​ Web Browser: A software application (e.g., Chrome, Firefox) that retrieves,
interprets and displays web pages from the internet using HTTP/HTTPS.

2. List some features of Unix.

●​ Multi-user system: Many users can work simultaneously.


●​ Multitasking: Can run multiple tasks/processes at the same time.
●​ Portability: Written in C, so easily adaptable to many hardware platforms.
●​ Security: File permissions and user access control ensure safe operations.

3. What is the role of Server?

●​ A server provides services such as file sharing, web hosting, database


access, or communication to client systems.
●​ It manages resources, processes client requests, and returns responses.
●​ Ensures reliability, availability and centralized control of services.
●​ Supports multiple clients simultaneously using networking protocols.

4. What are the basic operations of Server socket?

●​ socket(): Creates a socket endpoint.


●​ bind(): Assigns an IP address and port number to the socket.
●​ listen(): Allows the server to listen for incoming client connections.
●​ accept(): Accepts a client connection request and creates a new socket for
communication.
●​ send()/recv(): Exchanges data with the client.

5. Distinguish between absolute URL and relative URL.

●​ Absolute URL: Contains the complete address including protocol, domain,


path (e.g., [Link]
●​ Relative URL: Does not include domain; depends on the current page’s
location (e.g., /images/[Link]).
●​ Absolute = full path, Relative = partial path used within the same site.

6. What is the main function of a firewall?

●​ A firewall monitors and controls incoming and outgoing network traffic


based on predefined security rules.
●​ It acts as a barrier between trusted internal and untrusted external
networks.
●​ Prevents unauthorized access, attacks, and data breaches.
●​ Protects network resources by filtering packets.

7. What does Xerox Network System (XNS) mean?

●​ XNS is a networking protocol suite developed by Xerox Corporation.


●​ It provides routing, transport, and addressing protocols used in early
computer networks.
●​ Forms the basis for later protocols like Novell IPX/SPX.
●​ Known for early implementation of Ethernet communication standards.

8. Why do we need WAP?

●​ WAP (Wireless Application Protocol) enables internet access on mobile


devices with limited resources.
●​ Designed for low bandwidth, small screens, and low processing power.
●​ Provides standards for mobile browsing, messaging, and secure
communication.
●​ Allows delivery of web content in WML format optimized for wireless devices.

9. Why Network needs Security?

●​ To protect data from unauthorized access or modification.


●​ To maintain confidentiality, integrity, and availability.​

●​ To prevent attacks like viruses, hacking, spoofing, and data theft.


●​ Ensures reliable communication and safeguards organizational information.

10. What is a firewall?

●​ A firewall is a network security device/software that filters traffic based on


rules.
●​ It decides which packets to allow or block.
●​ Protects internal network from external threats and intrusions.
●​ Ensures safe communication by enforcing security policies.

11. Define Protocol.

●​ A protocol is a set of rules and conventions that governs communication


between devices in a network.
●​ Defines message formats, timing, error handling, and sequencing.
●​ Examples: TCP/IP, HTTP, FTP.

12. What is Data Encryption?

●​ Encryption is the process of converting plain text into unreadable


ciphertext using an algorithm and key.
●​ Protects data from unauthorized access.
●​ Only someone with the correct decryption key can read the original data.
●​ Used in SSL/TLS, email security, and data storage.

13. What are the differences between Encoding, Encrypting and Hashing?

●​ Encoding: Converts data into another format for compatibility (e.g., Base64).
Not for security.
●​ Encryption: Converts data into secret form using keys. Reversible with key.
●​ Hashing: Converts data into fixed-length hash value. Irreversible, used for
passwords, integrity checks.

14. Discuss Select and Poll functions.

●​ select(): Monitors multiple file descriptors (sockets) to check if they are ready
for read/write. Uses fixed-size FD sets.
●​ poll(): Similar to select but uses a dynamic array of file descriptors, supports
more descriptors efficiently.
●​ Both are used for I/O multiplexing to manage multiple connections in a single
thread.

15. What are Socket Options?

●​ Socket options allow the programmer to configure socket behavior.


●​ Set using setsockopt() and retrieved using getsockopt().
●​ Examples:
○​ SO_REUSEADDR (reuse port),
○​ SO_RCVBUF/SO_SNDBUF (buffer sizes),
○​ SO_KEEPALIVE (check active connection).
●​ Helps optimize performance and communication.

16. Name the three means of User Authentication.

1.​ Something you know: Password, PIN.


2.​ Something you have: Smart card, OTP token.
3.​ Something you are: Biometrics like fingerprint, face ID.

17. What is the difference between cat command and more command?

●​ cat: Displays entire file contents at once without pausing.


●​ more: Displays contents page by page, allowing user to scroll with spacebar.
●​ cat = continuous output, more = paginated output.

18. How to change the password in UNIX operating system?

●​ Use the command: passwd​


Steps:
1.​ Type passwd in terminal.
2.​ Enter current password.
3.​ Enter new password.
4.​ Confirm new password.
●​ System updates encrypted password in /etc/shadow.

19. Differentiate client and server.

●​ Client: Requests a service; initiates communication.


●​ Server: Provides service; waits for client requests.
●​ Client is generally lightweight, server is resource-heavy.
●​ Example: Browser (client) requesting webpage from web server

UNIT I

Q2 (a). What is I/O Multiplexing? Explain different types of Synchronous and


Asynchronous I/O Models.

1. Meaning of I/O Multiplexing

I/O Multiplexing allows a single process to monitor multiple I/O streams


(sockets/files) at the same time and know which one is ready for read or write.​
Instead of creating one thread per connection, a single process waits for events
using select(), poll(), epoll() etc.
Why it is used?

●​ Efficient handling of many clients (like chat servers or web servers)


●​ Saves CPU, memory, and avoids thread overhead
●​ Prevents blocking on a single socket

2. Types of I/O Models

I/O models describe how a process waits for data.

1. Blocking I/O (Synchronous)

●​ The simplest model.


●​ The process waits (blocks) until the data is available.
●​ Example: recv() blocks until data arrives.
●​ Easy to program but not suitable for many simultaneous connections.

Diagram:​
Process → recv() → wait → data arrives → return.

2. Non-Blocking I/O (Synchronous)

●​ The socket is put into non-blocking mode.


●​ The call returns immediately, even if data is not available.
●​ The application keeps checking (polling).
●​ Wastes CPU → inefficient for many connections.

3. I/O Multiplexing (Synchronous)

●​ Uses select() or poll() to check multiple sockets at once.


●​ Process sleeps until any socket becomes ready.
●​ After readiness, actual read/write functions are called.
●​ Good for servers handling many clients.

Steps:

1.​ Add all sockets to fd_set


2.​ Call select()
3.​ Select wakes when a socket has data
4.​ Server reads from that socket
4. Signal-Driven I/O (Asynchronous Notification)

●​ Application tells OS to send SIGIO signal when data is ready.


●​ Process continues doing other work until signal arrives.
●​ On signal, process performs read.
●​ Better than polling but rarely used due to complexity.

5. Asynchronous I/O (Truly Asynchronous)

●​ Application initiates an I/O operation → OS completes it in background.


●​ Application gets a notification when I/O operation is finished.
●​ Reads/writes happen without blocking or waiting.
●​ Most efficient but most complex.

Summary Table

Model Type Blocking Notes


?

Blocking I/O Sync Yes Simple but slow

Non-Blocking Sync No Requires repeated


polling

I/O Multiplexing Sync Yes/No Best for many clients

Signal-Driven Asyn No SIGIO not widely used


c

Asynchronous Asyn No Fastest, complex


I/O c

Q2 (b). Explain the following function calls with syntax, operation, and
necessity.

(i) socket()

Syntax:
int socket(int domain, int type, int protocol);

Operation:

●​ Creates a new socket endpoint.


●​ Returns a file descriptor used for communication.
●​ Domain: AF_INET, AF_INET6
●​ Type: SOCK_STREAM (TCP), SOCK_DGRAM (UDP)

Necessity:

●​ First step of network programming.


●​ Without creating a socket, communication cannot start.

(ii) bind()

Syntax:
int bind(int sockfd, const struct sockaddr *addr, socklen_t
addrlen);

Operation:

●​ Assigns a local IP address and port number to the socket.


●​ Ensures the server’s socket is accessible to clients.

Necessity:

●​ Required by servers to become reachable.


●​ For UDP, must bind before using recvfrom().
●​ Without bind, OS assigns a random port (not suitable for servers).

(iii) listen()

Syntax:
int listen(int sockfd, int backlog);

Operation:

●​ Converts a TCP socket into a passive (listening) socket.


●​ Creates a queue for incoming connection requests.

Necessity:

●​ Required for TCP servers.


●​ Without listen(), server cannot accept client connections.

(iv) recvfrom()
Syntax:
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t
*addrlen);

Operation:

●​ Receives a message from a socket (mostly UDP).


●​ Stores sender’s address in src_addr.
●​ For TCP, recv() is used, but UDP requires recvfrom().

Necessity:

●​ Used in connectionless communication (UDP).


●​ Helps identify which client sent the message since no connection exists.

Conclusion

All four functions form the foundation of socket programming:​


socket() → bind() → listen() → recvfrom()/accept() → communication.

Q3 (a). Write briefly about lack of flow control with UDP. List the difference
between TCP and UDP.
1. Lack of Flow Control in UDP

●​ UDP is connectionless, so it does NOT manage flow control.


●​ No mechanism like TCP’s window size to slow down sender.
●​ If sender transmits too fast, receiver may drop packets.
●​ Applications must implement their own flow control if needed.
●​ Suitable for real-time systems where speed matters more than reliability.

2. Differences Between TCP and UDP

(i) Connection

●​ TCP: Connection-oriented (3-way handshake)


●​ UDP: Connectionless

(ii) Reliability

●​ TCP: Reliable → acknowledgements, retransmissions


●​ UDP: Unreliable → no guarantee of delivery

(iii) Flow Control


●​ TCP: Provides automatic flow control (windowing)
●​ UDP: No flow control

(iv) Ordering

●​ TCP: Maintains sequence of packets


●​ UDP: No ordering

(v) Speed

●​ TCP: Slower due to overhead


●​ UDP: Faster and lightweight

(vi) Use Cases

●​ TCP: Web browsing, email, file transfer


●​ UDP: Video streaming, online gaming, DNS

Q3 (b). What is I/O Multiplexing? Explain different types of Synchronous and


Asynchronous I/O Models.

✔️YouThis is the SAME as Q2(a).​


can write the exact answer of Q2(a) again in the exam because both
questions are identical.

4. Explain with a suitable diagram the socket system calls used for
connection-oriented and connectionless communication between a client and
a server.

Socket programming supports two communication types:

A. Connection-Oriented Communication (TCP)

TCP requires a connection setup before data transfer.

➤ TCP SERVER SIDE SYSTEM CALLS

1.​ socket() – Create a socket.


2.​ bind() – Assign IP address + port.
3.​ listen() – Mark socket as passive (waiting for clients).
4.​ accept() – Accept client connection; returns new connected socket.
5.​ read()/write() or recv()/send() – Data exchange.
6.​ close() – Close connection.
➤ TCP CLIENT SIDE SYSTEM CALLS

1.​ socket() – Create client socket.


2.​ connect() – Request connection to server.
3.​ read()/write() – Data transfer.
4.​ close() – Close connection.

gpt

B. Connectionless Communication (UDP)

UDP does not require a connection. Packets are sent individually.

➤ UDP SERVER SIDE SYSTEM CALLS

1.​ socket() – Create UDP socket.


2.​ bind() – Assign IP & port.
3.​ recvfrom() – Receive datagrams from any client.
4.​ sendto() – Send reply to specific client.
5.​ close() – Close socket.

➤ UDP CLIENT SIDE SYSTEM CALLS

1.​ socket()
2.​ sendto() – Send datagram to server.
3.​ recvfrom() – Receive server reply.
4.​ close()

gpt
✔ UDP is fast, lightweight, no connection, no reliability, no flow control.

5. Explain the functionality provided by select function. List the differences


between poll and select functions.
A. select() Function – Meaning

select() is used for I/O multiplexing — it allows a program to monitor multiple


sockets at the same time and determine which one is ready for:

●​ Reading​

●​ Writing
●​ Exception handling
It prevents the server from blocking on a single socket and enables handling many
clients efficiently.

Syntax

int select(int nfds, fd_set *readfds, fd_set *writefds,


fd_set *exceptfds, struct timeval *timeout);

Functionality (Easy to Write)

1.​ You create fd_set groups (read, write, exception).


2.​ Add socket descriptors using FD_SET().
3.​ Call select().
4.​ select() blocks until:
○​ A socket becomes readable, or
○​ Writable, or
○​ Timeout occurs.​

5.​ After it returns, program checks which sockets are ready using FD_ISSET().​

select() Advantages

●​ Handles multiple connections with a single thread.


●​ Efficient for small to medium number of sockets.
●​ Portable across all operating systems.

B. Differences between poll() and select()

Feature select() poll()

Data Uses fixed-size fd_set Uses dynamic array of pollfd


structure

Max sockets Limited (usually 1024) No fixed limit

Modifying fds Must reset fd_set every time pollfd array remains intact

Performance Slower for large number of Better scalability


sockets

Portability Very widely supported Also supported but slightly less


universal

Kernel Bitmask-based scanning Structure-based scanning


behavior
Conclusion

select() and poll() are essential for building scalable servers.​


select() is simple and widely used, but poll() is preferred when handling many
socket descriptors due to better scalability.

6. Describe the OSI Reference Model and Unix Standards.

A. OSI Reference Model

OSI (Open Systems Interconnection) is a 7-layer framework that standardizes


networking functions.​
Each layer performs a specific job and communicates with the layer above and
below.

OSI Model Layers (Top to Bottom):

1. Application Layer

●​ Directly interacts with user applications.


●​ Services: HTTP, FTP, SMTP.

2. Presentation Layer

●​ Data translation, compression, encryption.


●​ Makes data understandable across systems.

3. Session Layer

●​ Manages sessions between systems.


●​ Establish, maintain, terminate connections.

4. Transport Layer

●​ End-to-end communication.
●​ TCP (reliable), UDP (unreliable).

5. Network Layer

●​ Routing and addressing.


●​ Protocol: IP.

6. Data Link Layer

●​ Frames, MAC addressing, error detection.


●​ Protocols: Ethernet, PPP.
7. Physical Layer

●​ Transmission of raw bits over physical medium.


●​ Cables, signals, voltage levels.

gpt

B. UNIX Standards

UNIX systems follow several standards to ensure compatibility across


implementations.

1. POSIX (Portable Operating System Interface)

●​ Most important standard.


●​ Defines APIs for process control, threading, files, signal handling.
●​ Ensures software portability across Unix/Linux systems.

2. SUS (Single UNIX Specification)

●​ Defines what qualifies as a “UNIX-compliant” OS.


●​ Includes POSIX + additional required utilities.

3. System V (SVR4) and BSD Standards

●​ Two major UNIX variants.


●​ System V: init, IPC (message queues, semaphores), terminal control.
●​ BSD: sockets, signals, networking stack.

4. Filesystem Hierarchy Standards

●​ Defines directory structures like /bin, /usr, /etc, /home.

UNIT II

4(a). What is DLL and what are their usages and advantages?

1. Meaning of DLL

A DLL (Dynamic Link Library) is a collection of functions and code modules that
can be used by multiple programs at the same time.​
Instead of embedding code in every executable, DLL stores reusable code in a
separate shared library file (e.g., .dll in Windows).

Examples: [Link], ws2_32.dll (Winsock), [Link].


2. Usages of DLL

1.​ Sharing common functionality​

○​ Multiple applications can call the same functions stored in a DLL, such
as printing, networking, GUI operations.​

2.​ Modular programming


○​ Large applications are divided into small modules stored as separate
DLLs.
3.​ Reducing memory and disk space usage
○​ Since many programs share the same DLL, duplicate code is avoided.
4.​ Dynamic loading of features
○​ A program can load a DLL at runtime using LoadLibrary() or
GetProcAddress().
5.​ Networking
○​ The Windows socket API (Winsock) is implemented in a DLL
(ws2_32.dll).
○​ It provides functions like socket(), bind(), connect(), etc.​

3. Advantages of DLL

(i) Efficient memory usage

DLL code is loaded into memory only once, even if multiple programs use it.

(ii) Easy upgrades

Updating a DLL instantly updates all applications that use it, without recompiling
them.

(iii) Reduced executable size

Executables become smaller because they do not contain all the code.

(iv) Faster application loading

Since many modules load only when needed, program startup becomes faster.

(v) Reusability

Commonly used functionalities (e.g., networking, encryption, graphics) are reusable


across multiple applications.

Perfect conclusion

DLLs improve modularity, reduce memory usage, enable dynamic loading, and make
applications easier to upgrade. They are essential in Windows networking and
system programming.
4(b). What are the advantages of Java Beans?

A Java Bean is a reusable software component written in Java that follows certain
conventions (getter/setter methods, no-arg constructor, serializable). Beans can be
visually manipulated in IDE tools.

Advantages of Java Beans

1. Reusability

Beans can be reused across different applications and projects.​


Example: A LoginBean or EmployeeBean can be used wherever required.

2. Portability

Beans are written in 100% Java, so they run on any platform with JVM.​
This makes them highly portable and platform-independent.

3. Easy to maintain

Beans are based on object-oriented principles:

●​ Encapsulation
●​ Modularity
●​ Well-defined interfaces

Thus, they are easy to modify and maintain over time.

4. Customization support

JavaBeans can be customized through property editors.​


Developers can change properties (color, size, behavior) visually in IDE tools.

5. Interoperability

Beans follow standard naming conventions and can interact easily with:

●​ JSP pages
●​ Servlets
●​ Enterprise Java components
●​ GUI builders

6. Persistence

Beans support serialization, allowing them to save and restore their state.

7. Visual Development Support

Beans work well with drag-and-drop GUI tools (like NetBeans, Eclipse).​
Developers can assemble UIs without writing much code.
5. Explain with diagrams the following I/O models provided by UNIX:

(i) Blocking I/O​


(ii) Non-blocking I/O​
(iii) Signal-driven I/O**

(i) Blocking I/O Model

Explanation

●​ In this model, system calls like read() and recv() block the process until
data is available.
●​ The process waits/ sleeps and cannot do anything else.
●​ Simple to implement but not efficient for high-performance servers.

Diagram (Exam-Friendly)

Process --> read() ------> [Blocked] ------> Data arrives


------> read() returns

(ii) Non-Blocking I/O Model

Explanation

●​ The socket is put into non-blocking mode.


●​ The read() call returns immediately, even if no data is available.
●​ Process must repeatedly poll (re-check) the socket.
●​ Reduces blocking but wastes CPU if many sockets are checked frequently.

Diagram

Process --> read()

--> No data? return immediately

Process continues work

(iii) Signal-Driven I/O Model

Explanation
●​ Process sets the socket to deliver SIGIO signal when data becomes ready.
●​ The process continues working until signal arrives.
●​ When SIGIO is received, application performs read() to fetch data.
●​ More efficient than non-blocking polling, but harder to implement.

Diagram

Process --> sets SIGIO handler

Process continues normal execution

|-----> OS sends SIGIO when data arrives

--> handler calls read()

Comparison

Model Blocking Efficienc Usage


? y

Blocking I/O Yes Low Simple clients

Non-blocking No Medium Servers with polling


I/O

Signal-driven No High Asynchronous event-driven


I/O servers

Conclusion

UNIX provides multiple I/O models to support different performance requirements.​


Blocking is simplest, non-blocking reduces wait time, and signal-driven I/O provides
asynchronous event notification suitable for high-performance networking
applications.
3. What are different properties of a Java Bean?

A Java Bean is a reusable component that follows specific conventions for property
access and manipulation.​
Properties define the state of a Bean and can be accessed using getter/setter
methods.

⭐ Types of Properties in Java Beans


1. Simple Properties

●​ Properties with a single value.


●​ Represented by standard getter/setter methods.​
Example:

getName(), setName(String n)

2. Indexed Properties

●​ Property that stores a list or array of values.


●​ Can access entire array or individual elements.​
Example:

getItem(int index), setItem(int index, value)

3. Bound Properties

●​ When a property changes, it notifies registered listeners.


●​ Used where other components must know state changes.
●​ Useful in GUIs or MVC applications.

4. Constrained Properties

●​ Similar to bound properties, but listeners may veto (reject) a property change.
●​ Supports validation before accepting the new value.

5. Read-Only Properties

●​ Only getter method is supplied.​


Example:

getId()

6. Write-Only Properties

●​ Only setter method is supplied.​


Example:

setSecret(String s)
⭐ Characteristics of Java Bean Properties
1.​ Follow naming conventions (getXxx(), setXxx()).
2.​ Are encapsulated, allowing controlled access.
3.​ Support introspection, meaning tools can automatically analyze bean
properties.
4.​ Ensure modularity and reusability of components.

Conclusion

Java Beans provide simple, indexed, bound, constrained, read-only, and write-only
properties, helping build modular, interactive, and reusable components in Java
applications.

4. What are the main functions in the socket API?

A socket API provides a set of system calls for creating, managing, and using
network communication endpoints.

⭐ Main Socket API Functions


1. socket()

●​ Creates a new socket descriptor.


●​ Parameters define protocol family (AF_INET), type (SOCK_STREAM/UDP).
●​ First step for both clients and servers.

2. bind()

●​ Assigns an IP address and port number to a socket.


●​ Used mainly by servers to make their address known to clients.

3. listen()

●​ Converts a socket into a passive TCP socket that waits for incoming
connections.
●​ Creates a queue for pending client requests.

4. accept()

●​ Accepts an incoming TCP connection request.


●​ Returns a new socket for communication with the client.​

5. connect()

●​ Used by the client to establish a connection with the server.


●​ Performs TCP three-way handshake.

6. send() / recv()
●​ Used in TCP communication for sending and receiving data.​

7. sendto() / recvfrom()

●​ Used in UDP (connectionless) communication.


●​ Requires specifying destination/source address each time.

8. close()

●​ Closes the socket and releases resources.

⭐ Supportive API Functions


getsockopt() / setsockopt()

●​ Get or modify socket options: buffer size, timeout, reuse address, keepalive,
etc.

select() / poll()

●​ Used for I/O multiplexing (monitoring multiple sockets).

Summary

The main socket API consists of functions for creating sockets, binding addresses,
listening, accepting connections, sending/receiving data, and closing sockets. These
functions form the core of all network programming.

5. What are the different API’s available in Winsock DLL?

Windows Networking is implemented using Winsock (Windows Sockets), primarily


in ws2_32.dll.

Winsock provides APIs that follow Berkeley sockets but include additional
Windows-specific functions.

⭐ Important Winsock APIs


1. WSAStartup()

●​ Initializes the Winsock library.


●​ Must be called before any socket operation.
2. WSACleanup()

●​ Cleans up Winsock resources.


●​ Called at program termination.

3. WSASocket()

●​ Creates a socket with extended options.


●​ More flexible than standard socket().

4. WSARecv() / WSASend()

●​ High-performance asynchronous send/receive functions.


●​ Support overlapped I/O and advanced flags.

5. WSAGetLastError()

●​ Retrieves detailed error information from Winsock.

6. getaddrinfo() / getnameinfo()

●​ Resolve hostnames to IP addresses and vice versa.

7. bind(), listen(), accept(), connect()

●​ Standard socket API functions, also available in Winsock.

8. closesocket()

●​ Closes a socket (Windows uses this instead of close()).

9. ioctlsocket()

●​ Control socket behavior (e.g., set non-blocking mode).

10. WSAEventSelect() / WSAWaitForMultipleEvents()

●​ Used for asynchronous event-based socket handling.

Summary

Winsock offers initialization functions (WSAStartup), asynchronous I/O functions


(WSARecv, WSASend), error handling, address resolution, event-handling APIs, and
standard socket calls — enabling powerful and flexible networking on Windows
systems.
6. How do I open a Socket?

Opening a socket means creating a communication endpoint using the


socket() system call.​
Both TCP and UDP sockets are opened in a similar way.

⭐ Steps to Open a Socket


Step 1 — Include Header Files

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

Step 2 — Call socket()

int sockfd = socket(AF_INET, SOCK_STREAM, 0);

●​ AF_INET → IPv4
●​ SOCK_STREAM → TCP (use SOCK_DGRAM for UDP)
●​ Returns a socket descriptor representing the endpoint.

Step 3 — Check for Errors

if (sockfd < 0) {

perror("Socket creation failed");

Step 4 — (Server Only) Use bind()

Assign IP and port:

bind(sockfd, (struct sockaddr *)&server_addr,


sizeof(server_addr));

Step 5 — (TCP Server Only) listen() + accept()

listen(sockfd, 5);

int newsock = accept(sockfd, NULL, NULL);


Step 6 — Use send()/recv() or sendto()/recvfrom()

Communicate with remote machine.

Step 7 — Close the socket

close(sockfd);

UNIT III

6(a). Describe the transport layer of WAP.

The Wireless Application Protocol (WAP) architecture is designed for mobile


devices with low bandwidth and limited processing power.​
The Transport Layer of WAP is mainly composed of Wireless Transport Layer
Security (WTLS) and Wireless Transaction Protocol (WTP), running over
Wireless Datagram Protocol (WDP).

⭐ Components of WAP Transport Layer


1. Wireless Datagram Protocol (WDP)

●​ Lowest layer of WAP transport.


●​ Provides a uniform interface to higher layers irrespective of the wireless
network used (GSM, CDMA, SMS, GPRS).
●​ Similar to UDP in the Internet model.
●​ Offers connectionless, low-overhead message delivery.

2. Wireless Transport Layer Security (WTLS)

●​ Provides security services:


○​ Authentication
○​ Encryption
○​ Data integrity
○​ Protection against replay attacks​

●​ Designed to work efficiently over wireless networks with high packet loss.
●​ Lightweight version of SSL/TLS.

3. Wireless Transaction Protocol (WTP)

●​ Handles transaction-oriented communication.


●​ Faster than traditional TCP because it is optimized for wireless conditions.
●​ Supports three classes of transactions:
○​ Unreliable one-way request
○​ Reliable one-way request
○​ Reliable two-way request-response
●​ Provides:​

○​ Acknowledgement mechanisms
○​ Duplicate removal
○​ Optional reliability (saves bandwidth)

⭐ Role of WAP Transport Layer


●​ Ensures efficient communication over unstable, low-bandwidth wireless
channels.
●​ Offers a balance of speed, reliability, and security.
●​ Makes higher WAP layers independent of underlying network technology.

Conclusion:

The WAP transport layer consists of WDP, WTLS, and WTP, which collectively
provide secure, optimized, and flexible communication suited for mobile wireless
devices.

6(b). Define in brief “Wireless Application Environment (WAE)”.

The Wireless Application Environment (WAE) is the application framework in


the WAP architecture that allows mobile devices to access web-like services.

⭐ Key Features of WAE


1. Provides Application Services

●​ Offers the environment for running lightweight mobile applications.


●​ Includes WML, WMLScript, and WTA (Wireless Telephony Applications).

2. Supports Wireless Browsing

●​ WAE contains the micro-browser used in mobile phones before


smartphones.
●​ WML pages (Wireless Markup Language) are downloaded from WAP servers.​

3. Device Independence

●​ WAE allows content developers to write applications once and run them
across different devices and networks.

4. Interoperability

●​ Provides standard APIs and functionality so applications behave consistently


across various wireless networks.​
5. Optimized for Wireless Constraints

●​ Efficient content formats (WML), compressed communication, small scripts.​

Conclusion

WAE is the top layer of WAP that defines how mobile devices display content, run
applications, and interact with users.​
It plays a similar role to the Application layer of the internet, but optimized for
wireless environments.

6(c). Difference between RMI and CORBA.

RMI (Remote Method Invocation) and CORBA (Common Object Request


Broker Architecture) are technologies used for communication between
distributed objects.

⭐ Differences Between RMI and CORBA


Feature RMI CORBA

Platform/Language Java-only Language independent (C++,


Support Java, Python, Ada, etc.)

Communication Java objects calling Heterogeneous distributed


Style methods remotely objects communicating using IDL

Interface Definition Uses Java interfaces Uses IDL (Interface Definition


Language)

Underlying Protocol JRMP (Java Remote IIOP (Internet Inter-ORB Protocol)


Method Protocol)

Security Model Uses Java Security Security defined by CORBA


Manager services
Ease of Use Simple (Java-friendly) Complex due to multi-language
support

Use Case Pure Java distributed Enterprise systems integrating


applications multiple languages

7(a). Explain in detail the various aspects of security.

Network security ensures confidentiality, integrity, authentication, authorization,


and availability of data during communication.​
Below are major aspects

⭐ 1. Confidentiality
●​ Ensures data is accessible only to authorized users.
●​ Achieved through encryption (e.g., AES, RSA).
●​ Prevents eavesdropping and unauthorized access.

⭐ 2. Integrity
●​ Protects data from being altered during transmission.
●​ Ensures message received = message sent.
●​ Achieved using hash functions, checksums, digital signatures.

⭐ 3. Authentication
●​ Verifies the identity of communicating parties.
●​ Methods:
○​ Passwords
○​ Certificates
○​ Biometrics
○​ Tokens

⭐ 4. Authorization
●​ Determines what a user is allowed to access after authentication.
●​ Example: Admin vs. Normal user privileges.
●​ Implemented using access control lists (ACLs) or policies.

⭐ 5. Non-Repudiation
●​ Ensures that a sender cannot deny sending a message later.
●​ Implemented using digital signatures.
●​ Important for legal and financial transactions.

⭐ 6. Availability
●​ Ensures systems and data remain accessible when needed.
●​ Protection against:
○​ DoS/DDoS attacks
○​ Hardware failures
○​ Power outages
●​ Achieved using redundancy, backups, load-balancing

⭐ 7. Privacy
●​ Ensures personal or sensitive data is protected from misuse.
●​ Regulations (GDPR, HIPAA) ensure privacy rights.

⭐ 8. Security Policies & Procedures


●​ Define rules for secure operation:
○​ Password guidelines
○​ Data handling procedures
○​ Operational controls
●​ Ensures consistent security enforcement.

7(b). What is the difference between a digital signature and an electronic


signature?

Both are used for authentication, but they differ in technology, security level,
and legal purpose.

⭐ Differences
Feature Digital Signature Electronic Signature

Definition Cryptographic mechanism that Any electronic method of


ensures authenticity and indicating agreement (typing
integrity of a document. name, clicking "I Agree").

Technology Uses public key cryptography Can be a simple image, typed


(PKI). name, OTP, etc.
Security Very high due to encryption + Lower security; depends on
Level hashing. method used.

Verification Verifiable using digital Often cannot be cryptographically


certificates. verified.

Tamper Detects even small data Does not detect tampering


Detection changes. reliably.

Legal Strong legal validity for Accepted but weaker in legal


Acceptance contracts, banking, disputes.
government.

Uniqueness Unique cryptographic identity Not unique; can be duplicated.


tied to the signer.

8. Explain the difference between Symmetric and Asymmetric Encryption.

Encryption is the process of converting plaintext into ciphertext to protect data from
unauthorized access.​
Encryption systems are mainly of two types: Symmetric and Asymmetric.

⭐ 1. Symmetric Encryption
Definition:

Uses the same key for both encryption and decryption.

How it works:

●​ Sender encrypts the message using a shared secret key.


●​ Receiver uses the same key to decrypt it.

Examples:

●​ AES
●​ DES
●​ 3DES
●​ Blowfish

Advantages:
●​ Very fast and efficient
●​ Suitable for encrypting large amounts of data
●​ Low computational cost

Disadvantages:

●​ Secure key exchange is difficult


●​ If the key is leaked, entire communication is compromised

⭐ 2. Asymmetric Encryption
Definition:

Uses two different keys — a public key for encryption and a private key for
decryption.

How it works:

●​ The public key is shared openly.


●​ Only the private key (kept secret) can decrypt the message.

Examples:

●​ RSA
●​ ECC
●​ DSA

Advantages:

●​ Secure key distribution


●​ Supports digital signatures
●​ Provides authentication

Disadvantages:

●​ Much slower than symmetric encryption


●​ Not suitable for encrypting large data directly

⭐ 3. Difference Table
Feature Symmetric Asymmetric Encryption
Encryption

Number of One key Two keys (public + private)


Keys
Speed Fast Slow

Security Less secure (single More secure (key pairs)


key)

Key Sharing Difficult Easy (public key can be distributed


freely)

Used For Bulk data encryption Key exchange, digital signatures

Examples AES, DES RSA, ECC

⭐ Conclusion
Symmetric encryption is fast and suitable for data encryption, while asymmetric
encryption provides secure key exchange and authentication. In modern systems,
both are often used together for maximum security.

9. Why do we need WAP?

WAP (Wireless Application Protocol) was designed to allow mobile devices to access
internet-like services over wireless networks that have:

●​ Low bandwidth
●​ High latency
●​ Small screens
●​ Limited processing power

⭐ Reasons Why WAP Is Needed


1. Accessing Internet Services on Mobile Phones

Early mobile devices could not run full HTML browsers.​


WAP enabled web browsing through WML pages optimized for mobile screens.

2. Overcoming Wireless Limitations


Mobile networks were slow (9.6 kbps), unreliable, and expensive.​
WAP provided compressed, efficient data exchange suitable for these networks.

3. Providing a Standard Framework

WAP standardized communication for all mobile devices, irrespective of:

●​ Network type (GSM, CDMA, SMS, GPRS)


●​ Device manufacturer

4. Supporting Wireless Applications

Enabled services such as:

●​ Email
●​ Stock quotes
●​ Weather forecast
●​ Mobile banking
●​ Messaging

5. Security over Wireless Networks

WAP included WTLS, a lightweight security layer for authentication and encryption.

6. Device and Network Independence

Content created using WAP standards runs on all WAP-enabled phones, ensuring
interoperability.

10. What are the different layers of WAP Architecture?

The WAP architecture is similar to the OSI model but optimized for mobile devices.​
It is structured into five layers, each handling a specific communication function.

⭐ WAP Architecture Layers (Top to Bottom)


1. Wireless Application Environment (WAE)

●​ Topmost layer.
●​ Provides the application framework (micro-browser, WML, WMLScript).
●​ Supports services like telephony (WTA) and user interface management.
●​ Equivalent to Application layer of internet.

2. Wireless Session Protocol (WSP)

●​ Manages sessions between client and WAP gateway.


●​ Provides session services like connection establishment, re-establishment,
suspension.
●​ Similar to HTTP but lighter.

3. Wireless Transaction Protocol (WTP)

●​ Provides transaction-oriented communication.


●​ Supports reliable/unreliable request-response operations.
●​ Faster than TCP for wireless networks.

4. Wireless Transport Layer Security (WTLS)

●​ Provides encryption, authentication, and data integrity.


●​ Lightweight version of TLS/SSL designed for wireless environments.

5. Wireless Datagram Protocol (WDP)

●​ Lowest layer of WAP architecture.


●​ Provides uniform interface to underlying bearer networks like GSM, SMS,
CDMA.
●​ Works like UDP in the TCP/IP model.

⭐ Diagram
WAE

WSP

WTP

WTLS

WDP

------------------ (Bearer Networks: GSM, SMS, GPRS)

11. What is a firewall? How do you set it up?

What is a Firewall?

A firewall is a network security system (hardware or software) that monitors and


controls incoming and outgoing traffic based on predefined security rules.​
It acts as a barrier between a trusted internal network and an untrusted external
network (e.g., Internet).

Functions of a Firewall:

●​ Blocks unauthorized access


●​ Allows legitimate communication
●​ Prevents attacks (malware, intrusion, port scanning)
●​ Enforces security policies
●​ Protects internal resources

⭐ How to Set Up a Firewall?


Steps apply to both hardware and software firewalls.

Step 1: Define Security Policies

●​ Identify which services need to be allowed (HTTP, FTP, SSH).


●​ Identify which ports and protocols must be blocked.
●​ Define rules for inbound and outbound traffic.

Step 2: Configure Firewall Rules

Common configurations:

●​ Allow trusted IP addresses


●​ Deny unwanted ports
●​ Enable default deny (block all → allow specific)
●​ Set rules for packet filtering, NAT, port forwarding

Step 3: Enable Logging & Monitoring

●​ Turn on logs to track blocked attempts


●​ Monitor unusual access patterns
●​ Review alerts for suspicious activity

Step 4: Update Firmware / Software

●​ Keep firewall updated with latest patches


●​ Prevents exploitation of known vulnerabilities

Step 5: Test Configuration

●​ Use tools like ping, traceroute, nmap


●​ Verify that blocked ports cannot be accessed
●​ Ensure required services are working

Step 6: Maintain Regular Updates

●​ Review firewall rules periodically


●​ Remove outdated rules
●​ Adjust for new network needs

12. Explain the technical details of firewall and the three types of firewall with
neat diagram.
A firewall filters network packets based on rules that inspect addresses, ports,
protocols, and connection states.​
Technical operations involve packet filtering, NAT, proxying, and monitoring.

⭐ Technical Details of Firewall


1. Packet Filtering

●​ Inspects each packet’s IP header (source, destination, port, protocol).


●​ Allows or blocks packets based on rules.
●​ Operates at Network Layer (Layer 3).

2. Stateful Inspection

●​ Tracks the state of connections (SYN, ACK, FIN).


●​ Allows packets only if part of a valid, established connection.
●​ More secure than simple packet filtering.
●​ Works at Layer 3 and 4.

3. Application Layer Filtering (Proxy Firewall)

●​ Inspects actual data inside packets (HTTP requests, FTP commands).


●​ Can block harmful content, malware, or forbidden websites.
●​ Operates at Layer 7 (Application Layer).

4. NAT (Network Address Translation)

●​ Hides internal IP addresses


●​ Helps prevent direct access to internal hosts

5. Logging and Alerting

●​ Records illegal access attempts


●​ Alerts the administrator for attacks

⭐ Types of Firewalls)
There are three major types of firewalls:

1. Packet Filtering Firewall

Diagram

Internet -----> [ Packet Filter ] -----> Internal Network

(Checks IP, Port, Protocol)


Features

●​ First generation firewall


●​ Filters based only on header information
●​ Fast but less secure
●​ No deep inspection

2. Stateful Inspection Firewall

Diagram

Internet --> [ Stateful Firewall ] --> Internal Network

(Maintains Connection Table)

Features

●​ Tracks connection states (SYN, ACK)


●​ Allows packets that belong to valid sessions
●​ More secure than packet filtering

3. Application Layer Firewall (Proxy Firewall)

Diagram

Internet --> [ Proxy Server ] --> Internal Host

(Inspects Application Data)

Features

●​ Deep inspection of HTTP, FTP, SMTP messages


●​ Can block malicious content
●​ Highest security but slower

⭐ Summary Table
Firewall Type Laye Securit Speed
r y

Packet Filter L3 Low Fast

Stateful Firewall L3/L4 Medium Mediu


m
Application L7 High Slower
Firewall

✅ 13. List some features of JavaScript.


JavaScript is a lightweight, interpreted scripting language mainly used for building
dynamic web pages.

⭐ Features of JavaScript
1. Lightweight and Interpreted

●​ Does not require compilation


●​ Browser directly interprets code
●​ Makes development fast

2. Object-Based Language

●​ Supports objects, properties, and methods


●​ Uses prototypes instead of classical inheritance

3. Client-Side Execution

●​ Runs in the browser, reducing load on the server


●​ Provides quick feedback to users

4. Event-Driven Programming

●​ Responds to user actions like clicks, input, mouse movement


●​ Makes web pages interactive

5. Dynamic Typing

●​ No need to declare variable types


●​ Type is determined at runtime

6. Cross-Platform Support

●​ Runs on all major browsers and operating systems


●​ Makes it highly portable

7. Built-in Support for HTML and CSS Manipulation

●​ Can modify DOM elements dynamically


●​ Used to create animations, validate forms, update content

8. Supports Functional Programming


●​ Functions are first-class objects
●​ Can be passed as arguments, returned from functions

9. Rich Libraries and Frameworks

●​ Has strong ecosystem: React, Angular, Vue, [Link]


●​ Widely used for front-end and back-end development

10. Asynchronous Programming Support

●​ Provides callbacks, promises, async/await​

●​ Handles network calls efficiently without blocking​

UNIT IV

8(a). Explain the various components of a URL with an example stating the
various methods to extract each component.

A URL (Uniform Resource Locator) specifies the address of a resource on the


internet.​
It defines how to access the resource and where it is located.

⭐ Components of a URL
Example URL:

[Link]

Breakdown:

1. Scheme / Protocol

●​ Defines the protocol used to access the resource.​

●​ Examples: http, https, ftp, mailto​


In the example:​
https

2. Host / Domain Name

●​ The server where the resource is hosted.​


Example:​

[Link]

3. Port Number

●​ Optional. Specifies the communication port.​

●​ Default ports: 80 (HTTP), 443 (HTTPS)​


Example:​

8080

4. Path

●​ The location of the resource on the server.​


Example:​

/products/item1

5. Query String

●​ Additional data passed to the server, often key-value pairs.​


Example:​

?id=25
6. Fragment / Anchor

●​ Points to a specific section of the resource.​


Example:​

#details

⭐ Methods to Extract URL Components (Using Java URL Class)


Java provides the [Link] class for parsing URLs.

Example Code

URL url = new


URL("[Link]
");

[Link](); // https

[Link](); // [Link]

[Link](); // 8080

[Link](); // /products/item1

[Link](); // id=25

[Link](); // details

⭐ Conclusion
A URL contains protocol, host, port, path, query, and fragment.​
The Java URL class provides easy methods to extract each component for network
programming.

8(b). Explain in detail the General format of an HTTP request security.

An HTTP request is a message sent by a client (browser) to a server to request a


resource.​
Security in HTTP requests is provided through HTTPS, headers, and authorization
mechanisms.

⭐ Structure of an HTTP Request


1. Request Line

Defines method, resource path, and HTTP version.

Example:

GET /[Link] HTTP/1.1

2. Request Headers

Provide additional information to the server, such as:

●​ Host: domain name​

●​ User-Agent: browser info​

●​ Accept: accepted content types​

●​ Authorization: credentials​

●​ Cookie: session data​

●​ Content-Type: data format in POST request​

Example:

Host: [Link]
User-Agent: Mozilla/5.0

Accept: text/html

3. Blank Line

Separates headers from the message body.

4. Message Body (Optional)

Used mainly in POST, PUT requests.

Example:

username=abc&password=123

⭐ HTTP Request Security Mechanisms


1. HTTPS (HTTP over SSL/TLS)

●​ Encrypts entire communication.​

●​ Protects confidentiality and integrity.​

●​ Prevents eavesdropping and tampering.​

2. Authentication

Methods include:

●​ Basic Authentication (Base64 encoded credentials)​

●​ Token-based authentication​

●​ OAuth​

●​ API Keys​
3. Authorization

●​ Ensures users access only allowed resources.​

●​ Implemented using RBAC (Role-Based Access Control).​

4. Cookies & Session Security

●​ HttpOnly cookies prevent JavaScript access.​

●​ Secure cookies only sent over HTTPS.​

●​ Prevents session hijacking.​

5. Input Validation

●​ Prevents attacks like SQL Injection and XSS.​

⭐ Conclusion
An HTTP request contains a request line, headers, optional body, and uses security
mechanisms like HTTPS, authentication, and secure cookies to protect
communication.

9(a). What are the differences between HTTP GET and HTTP POST?

Feature GET POST

Data Location Sent in URL Sent in message body


Security Less secure (visible in More secure than GET
URL)

Data Size Limited No significant limit

Use Case Data retrieval Data submission to


server

Idempotency Idempotent Not necessarily


idempotent

Browser Can be cached Not cached


Caching

Bookmarking Can be bookmarked Cannot be bookmarked

⭐ Explanation Summary
●​ GET is used for retrieving data; POST is used for sending data.​

●​ GET parameters appear in the URL, while POST stores data in the body.​

●​ POST is preferred for sensitive information (passwords, forms).​

9(b). Write the various steps which are involved in creating a server program.

A TCP server follows a sequence of socket system calls to establish communication.

⭐ Steps to Create a Server Program


1. Create a socket

socket(AF_INET, SOCK_STREAM, 0);

2. Bind the socket

Assign IP and port:

bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));

3. Listen for connections

listen(sockfd, backlog);

●​ Converts socket into passive listening mode.​

4. Accept client connection

new_socket = accept(sockfd, NULL, NULL);

●​ Establishes connection with client.​

5. Communicate with client

Use:

read(), write(), send(), recv()

6. Close client and server sockets


close(new_socket);

close(sockfd);

⭐ Diagram (Exam-Friendly)
socket() → bind() → listen() → accept() → send/recv → close()

Conclusion

A server must create a socket, bind it, listen for clients, accept connections,
exchange data, and close the connections.

9(c). What is the use of URL class?

The [Link] class provides a high-level abstraction for dealing with Uniform
Resource Locators in Java programs.

⭐ Uses of URL Class


1. Parsing a URL

It allows extraction of URL components such as:

●​ Protocol​

●​ Host​

●​ Port​

●​ File​

●​ Path​
●​ Query​

●​ Reference​

Example:

[Link]();

[Link]();

2. Establishing a Connection

The URL class can open a connection to the resource:

URLConnection conn = [Link]();

3. Reading Data from the Internet

Use input streams to read content:

InputStream in = [Link]();

4. Handling Remote Resources

Used for downloading files, reading web pages, and interacting with REST APIs.

5. Ensuring Platform Independence

URL class automatically handles formatting differences between systems.

10. A server will normally accept multiple incoming connections from clients.
This means it has to accept() and recv() multiple data at the same time.

A server often handles many clients simultaneously. If the server used only one
blocking socket, it would freeze while waiting for one client.​
To manage multiple clients, servers use I/O multiplexing, multi-threading, or
event-driven techniques.

⭐ 1. Problem with Single Connection


●​ accept() blocks until a client connects.​

●​ recv() blocks until data comes from a single client.​

●​ If one client is slow or idle, the entire server becomes unresponsive.​


Thus, servers must handle multiple connections simultaneously.​

⭐ 2. Techniques to Accept and Receive Multiple Connections


(A) I/O Multiplexing (select() / poll() / epoll())

Most commonly used method.

How it works:

1.​ Server puts all connected client sockets in a list.​

2.​ Calls select() or poll() to wait for readiness.​

3.​ OS tells which sockets have data or connection requests waiting.​

4.​ Server processes them one-by-one in a single loop.​

Advantages:

●​ Efficient​

●​ No need for multiple threads​

●​ Handles thousands of connections (epoll)​

(B) Multi-threaded Server


Server creates one thread per client.

Flow:

●​ Main thread runs accept()​

●​ For every new connection, spawn a new thread​

●​ Each thread handles recv() independently​

Advantages:

●​ Simple​

●​ Parallel execution​

Disadvantages:

●​ Heavy memory usage​

●​ Difficult to scale thousands of connections​

(C) Forking Server (Process per Client)

●​ Server forks a new child process for each client.​

●​ Used in older UNIX servers.​

(D) Asynchronous I/O

●​ OS notifies server when data is ready (using signals or AIO).​

●​ Server doesn’t block.​

⭐ Conclusion
A real-world server uses select(), poll(), epoll(), threads, or asynchronous I/O to
accept many client connections and receive data simultaneously, ensuring
responsiveness and scalability.

✅ 11. Briefly explain how to monitor several sockets at the same time.
Monitoring multiple sockets is essential for a server that handles many clients.​
This process is done using I/O multiplexing techniques, mainly select(), poll(),
and epoll().

⭐ 1. Using select()
Steps:

1.​ Create fd_set structures for read, write, exception.​

2.​ Add multiple socket descriptors to these sets.​

3.​ Call:​

select(maxfd + 1, &readfds, &writefds, NULL, &timeout);

4.​ select() returns when any socket is ready.​

5.​ Use FD_ISSET() to check which socket has data.​

Advantages:

●​ Simple and portable.​

⭐ 2. Using poll()
●​ poll() uses an array of pollfd structures instead of fixed-size fd_set.​

●​ Can monitor any number of sockets.​


●​ More scalable than select.​

Syntax:

poll(fds, nfds, timeout);

⭐ 3. Using epoll() (Linux only)


●​ Best for high-performance servers.​

●​ Uses an event-driven mechanism.​

●​ Suitable for thousands of connections.​

⭐ 4. Using WSAEventSelect() (Windows)


●​ Works with event objects.​

●​ Notifies which socket event occurred.​

⭐ 5. Multi-threading (Alternative)
●​ Each thread monitors one socket.​

●​ Simple but not efficient for many clients.​

12. Consider the TCP Echo Server and TCP Echo Client and discuss what
happens to the client when the server process crashes.

A TCP Echo server receives data from a client and sends the same data back.​
But if the server process crashes or terminates unexpectedly, TCP handles it in a
defined way.
⭐ 1. Before Server Crash
●​ Connection is established via 3-way handshake.​

●​ Client sends data → server echoes it back.​

⭐ 2. When the Server Crashes


Several things happen at the TCP level:

(A) Server process terminates → its socket closes

●​ Kernel automatically sends a TCP RST (reset) packet to the client.​

●​ This indicates that the connection is no longer valid.​

(B) What client experiences depends on its next action:

1. If the client tries to send data after server crash:

●​ Client receives an error such as:​

Connection reset by peer

●​ send() or write() fails immediately.​

2. If the client tries to read after server crash:

There are two possibilities:

Case 1: Server process crashes but OS still sends FIN

●​ Client reads 0 bytes, indicating connection closed normally.​

Case 2: Server crashes abruptly


●​ Client receives RST → read() fails with error.​

3. If client is idle and does nothing:

●​ Client remains unaware until it tries to read/write.​

⭐ 3. Timeout Case
If the server machine crashes but OS doesn’t send FIN/RST, client may wait until
TCP timeout occurs.​
This leads to:

ETIMEDOUT

⭐ Conclusion
When a TCP server crashes:

●​ Client gets RST or FIN signals​

●​ Reads return 0 or errors​

●​ Writes fail with "Connection reset by peer"​

TCP ensures the client eventually knows the server is unavailable.

✅ 13. What is the difference between client-side and server-side programming


language?

Client-side and server-side refer to where the code is executed in a web


application.

⭐ Client-Side Programming
Executed on:

●​ The user's browser​

Purpose:

●​ Enhance user experience​

●​ Handle interface interactions​

●​ Validate forms before sending to server​

●​ Manipulate HTML/CSS (DOM)​

Examples:

●​ JavaScript​

●​ HTML/CSS (markup, styling)​

Characteristics:

●​ Faster response (no server communication needed for UI changes)​

●​ Cannot access server files or databases​

●​ Less secure (code visible to users)​

⭐ Server-Side Programming
Executed on:

●​ The web server​

Purpose:

●​ Process data​

●​ Access database​

●​ Authenticate users​
●​ Generate dynamic web pages​

●​ Handle business logic​

Examples:

●​ PHP​

●​ Java (Servlets/JSP)​

●​ Python (Django)​

●​ [Link]​

●​ [Link]​

Characteristics:

●​ More secure​

●​ Can store, retrieve, and process large data​

●​ Slower response (requires network communication)​

⭐ Difference Table
Feature Client-Side Server-Side

Execution Browser Server

Security Low High

Access to No Yes
DB
Speed Fast for UI Depends on server
load

Visibility Code visible Code hidden

Use Cases UI Data processing


interactions

You might also like