0% found this document useful (0 votes)
6 views

5B Sockets PDF

This document provides an overview of socket programming, focusing on the mechanisms that allow processes on different devices to communicate over a network. It covers key concepts such as socket types, connections, attributes, and addresses, as well as the functions used for establishing connections like connect() and bind(). The content is structured into sections that detail the process of socket communication and the protocols involved, making it a comprehensive resource for understanding network IPC.

Uploaded by

sandeep bhukya
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)
6 views

5B Sockets PDF

This document provides an overview of socket programming, focusing on the mechanisms that allow processes on different devices to communicate over a network. It covers key concepts such as socket types, connections, attributes, and addresses, as well as the functions used for establishing connections like connect() and bind(). The content is structured into sections that detail the process of socket communication and the protocols involved, making it a comprehensive resource for understanding network IPC.

Uploaded by

sandeep bhukya
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
You are on page 1/ 26

KR21 - B.

Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Unit -5B: Introduction to Sockets

Syllabus

S. No Name of the Topic Page No.


1 Introduction to Sockets
2
o Sockets
2 o Socket Connections 3
3 o Socket attributes 5
4 o Socket addresses 6
5 o Socket
 connect() 7
 bind() 9
 listen() 10
 accept() 11
6 o Socket communications 12
7 Program for Client – Server communication using
14
sockets
8 PPT Slides 21

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 1
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Sockets
Sockets are a fundamental communication mechanism that allows processes (programs) running
on different devices or computers to establish a network connection and exchange data. Sockets
are widely used in network programming to enable communication between a client application
and a server application over the internet or a local network.
A socket is a software endpoint that represents one side of a communication channel. A server
socket is used by a server application to listen for incoming client connections, while a client socket
is used by a client application to initiate a connection to the server.
Here's how the socket communication process typically works:
1. Server Socket Setup: The server creates a socket and binds it to a specific IP address and
port number on the host machine. This is done to specify the interface through which the
server will listen for incoming connections.
2. Client Socket Setup: The client creates a socket and specifies the IP address and port
number of the server to which it wants to connect.
3. Connection Establishment: The client attempts to connect to the server by sending a
connection request to the server's IP address and port number.
4. Server Connection Acceptance: The server's socket, which is actively listening for
incoming connections, accepts the client's connection request and establishes a connection
with the client socket. This creates a dedicated communication channel between the client
and server.
5. Data Exchange: Once the connection is established, both the client and server can send
and receive data through their respective sockets. Data can be transmitted in both directions
simultaneously, allowing for real-time communication.
6. Connection Termination: When the communication is complete or either party wants to
end the connection, they can close their sockets, terminating the connection.
Sockets can operate using different communication protocols, such as TCP (Transmission Control
Protocol) or UDP (User Datagram Protocol). TCP ensures reliable, ordered, and error-checked
delivery of data, while UDP provides a faster, connectionless, and less reliable communication
method.
Socket programming involves using specific libraries or APIs provided by the programming
language to work with sockets. For example, in Python, you can use the socket module to create
and manage sockets, while other programming languages have their own socket libraries.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 2
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket Connections
Socket connections are a fundamental concept in computer networking, allowing processes
running on different devices or computers to communicate and exchange data over a network.
Sockets provide a bi-directional communication channel that enables applications to send and
receive data reliably and efficiently.
The key components of a socket connection are the client socket and the server socket. Here's a
breakdown of how socket connections work:
1. Client Socket:
 The client socket is created by a client application when it wants to communicate
with a server.
 The client socket specifies the IP address and port number of the server it wants to
connect to.
 Once the connection is established, the client socket can send data to and receive
data from the server socket.
2. Server Socket:
 The server socket is created by a server application to listen for incoming client
connections.
 The server socket is bound to a specific IP address and port number on the server
machine, specifying the interface through which the server will accept connections.
 When a client attempts to connect, the server socket accepts the connection and
establishes a dedicated communication channel with the client socket.
3. Establishing a Connection:
 To initiate a connection, the client sends a connection request to the server's IP
address and port number.
 The server's socket, which is actively listening for incoming connections, accepts
the client's request, creating a connection.
4. Data Exchange:
 Once the connection is established, both the client and server can send and receive
data through their sockets.
 Data can be transmitted in both directions simultaneously, enabling real-time
communication.
5. Protocol and Data Handling:
 Sockets can use different communication protocols, such as TCP or UDP,
depending on the requirements of the application.
 TCP (Transmission Control Protocol) ensures reliable, ordered, and error-checked
delivery of data. It is commonly used for applications that require data integrity and
guaranteed delivery.
 UDP (User Datagram Protocol) is connectionless and provides faster, lower
overhead communication. It is suitable for applications where speed is crucial, and
some data loss is acceptable.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 3
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

6. Connection Termination:
 When the communication is complete or either party wants to end the connection,
they can close their sockets, terminating the connection.
 Properly closing sockets is essential to release network resources and ensure that
the connection is cleanly terminated.
Socket connections are extensively used in various networked applications, including web
browsing, email communication, file transfers, online gaming, video streaming, and more. Socket
programming is supported by most programming languages, and each language has its own set of
libraries or APIs to handle socket communication.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 4
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket Attributes
In the context of socket programming, socket attributes refer to the properties or settings associated
with a socket object that can be used to control its behavior and characteristics. These attributes
provide developers with the flexibility to customize socket communication according to their
specific requirements. The exact set of attributes may vary depending on the programming
language or library being used, but some common attributes include:
1. IP Address and Port Number: Every socket is associated with an IP address and a port
number. For server sockets, the IP address and port number represent the local address the
server is bound to. For client sockets, they define the destination server's address.
2. Socket Type: Sockets can be of different types, such as stream sockets (e.g., TCP) or
datagram sockets (e.g., UDP). The type determines the communication mode and reliability
of the socket.
3. Protocol: The communication protocol used by the socket, such as TCP, UDP, or others.
The choice of the protocol affects how data is transmitted and received.
4. Blocking/Non-blocking Mode: In blocking mode, socket operations (e.g., sending or
receiving data) will wait until the operation is completed. In non-blocking mode, these
operations return immediately, and the application needs to handle any potential delays or
errors.
5. Timeout: A timeout value specifies the maximum time a socket operation can wait before
returning an error if no data is available or the connection cannot be established.
6. Buffer Size: The buffer size refers to the amount of memory allocated for data transmission
and reception. Larger buffer sizes can increase performance but may also consume more
memory.
7. Socket Options: Socket options are settings that control various aspects of socket
behavior. Examples include setting socket-level timeouts, enabling or disabling certain
features, and specifying the size of the receive and send buffers.
8. Multicast Options (for UDP): For UDP sockets, multicast options allow a socket to
participate in multicast group communication. This allows a single datagram to be sent to
multiple recipients.
9. Keep-Alive: The keep-alive attribute, if enabled, allows the socket to send periodic keep-
alive messages to check if the connection is still active.
10. Socket Family: The socket family determines the address format used for the socket.
Common families include IPv4, IPv6, and Unix domain sockets.
These attributes can be set and modified using specific functions or methods provided by the socket
library or programming language. It's essential for developers to understand and properly
configure these attributes to establish reliable and efficient communication between client and
server applications.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 5
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket Addresses
In socket programming, a socket address, also known as a network address, is used to identify and
locate a networked device or application within a network. It consists of two main components: an
IP address and a port number. Together, these components uniquely define the endpoint of a
communication channel, allowing data to be sent to and received from a specific process on a
specific device.
1. IP Address:
 An IP (Internet Protocol) address is a numerical label assigned to each device
connected to a computer network that uses the Internet Protocol for communication.
It serves as the device's identifier on the network.
 IPv4 addresses are written in the format of four decimal numbers separated by dots
(e.g., 192.168.0.1).
 IPv6 addresses are longer and written in a hexadecimal format (e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334).
2. Port Number:
 A port number is a 16-bit unsigned integer (ranging from 0 to 65535) used to
identify a specific process or service running on a device. It allows multiple services
to operate on the same device simultaneously.
 Well-known port numbers (0 to 1023) are reserved for standard services (e.g.,
HTTP uses port 80, HTTPS uses port 443), while registered (1024 to 49151) and
dynamic (49152 to 65535) ports are used for various applications.
When combined, the IP address and port number form a socket address, uniquely identifying a
specific network endpoint. In the case of client-server communication:
 The client needs the server's socket address to connect to it. The server socket address
consists of the server's IP address and the port number it is listening on for incoming
connections.
 The server uses its own IP address and the port number assigned to the client's connection
to send data back to the specific client.
For example, a server socket address could be represented as "192.168.0.1:8080," where
"192.168.0.1" is the server's IP address, and "8080" is the port number. The client uses this socket
address to connect to the server and initiate communication.
Socket addresses are essential for establishing connections in client-server architectures and
enabling data exchange across different devices on a network. Socket programming libraries and
APIs provide functions to work with socket addresses and handle communication between
processes on different devices using these addresses.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 6
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket – connect( )
In socket programming, the connect() function is used by a client to establish a network connection
to a server. This function is typically employed in the context of TCP (Transmission Control
Protocol) sockets, which provide reliable, stream-oriented communication.
The connect() function performs the following steps:
1. Create a Socket:
Before attempting to connect to a server, the client creates a socket using the socket()
function. This creates a communication endpoint that will be used to send and receive data
over the network.
2. Set Up Server Socket Address:
The client needs to know the server's socket address (IP address and port number) to
establish a connection. The server socket address specifies where the server is listening for
incoming client connections.
3. Call the connect() Function:
Once the client has the server's socket address, it calls the connect() function, passing the
socket descriptor (a unique identifier for the client's socket) and the server's socket address
as arguments.
The connect() function tries to establish a connection to the server using the specified
address.
4. Three-Way Handshake:
The connect() function initiates a three-way handshake with the server to establish a TCP
connection. This involves a series of messages exchanged between the client and the server
to ensure both parties agree to establish the connection.
The three steps of the handshake are: SYN (synchronize), SYN-ACK (synchronize-
acknowledge), and ACK (acknowledge).
5. Connection Established:
If the server accepts the client's connection request, and the three-way handshake completes
successfully, the connect() function returns, indicating that the connection is established.
The client can now start sending data to the server or receiving data from it through the
established connection.
6. Handle Connection Errors:
The connect() function may return an error if it cannot establish a connection to the server.
Common reasons for connection failure include the server not being reachable, the server
socket being unavailable, or the network being down.
Here's a simplified example of how the connect() function might be used in C:

#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 7
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

 sockfd -
o This is the file descriptor of the socket that you want to use for the connection.
o The sockfd should be a valid socket descriptor obtained from a previous call to the
socket() function.
 addr -
o A pointer to a struct sockaddr representing the address of the server to which you
want to connect.
o The struct sockaddr is a generic structure used to hold various types of socket
addresses (IPv4, IPv6, Unix domain, etc.).
o To use the struct sockaddr_in structure for IPv4 addresses, you'll need to cast the
addr pointer appropriately (e.g., (struct sockaddr*)&server_address).
 addrlen -
o The size of the addr structure in bytes.
o It is essential to provide the correct size of the addr structure to prevent buffer
overflows and ensure proper address resolution.
o For IPv4 addresses, the size would be sizeof(struct sockaddr_in).
The connect() function is used to establish a TCP connection between the client and the server.
Before calling this function, you should have already created a socket using the socket() function,
set up the server's address details in a struct sockaddr, and filled in the appropriate socket address
family, IP address, and port number.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 8
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket - bind( )
In C socket programming, the bind() function is used to associate a socket with a specific network
address, including an IP address and a port number. This is typically done on the server side to set
up the server's endpoint, allowing clients to connect to it.
Here's the syntax of the bind() function:

#include <sys/socket.h>

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

let's explain each parameter:


 sockfd -
o This is the file descriptor of the socket you want to bind.
o The sockfd should be a valid socket descriptor obtained from a previous call to the
socket() function.
 addr -
o A pointer to a struct sockaddr representing the network address you want to bind
the socket to.
o The struct sockaddr is a generic structure used to hold various types of socket
addresses (IPv4, IPv6, Unix domain, etc.).
o To use the struct sockaddr_in structure for IPv4 addresses, you need to cast the addr
pointer appropriately (e.g., (struct sockaddr*)&server_address).
 addrlen -
o The size of the addr structure in bytes.
o It is essential to provide the correct size of the addr structure to prevent buffer
overflows and ensure proper address resolution.
o For IPv4 addresses, the size would be sizeof(struct sockaddr_in).
The purpose of the bind() function is to set the local address of the socket, allowing the operating
system to direct incoming connection requests to the specified IP address and port number.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 9
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket - listen( )
In C socket programming, the listen() function is used on the server side to make a bound socket
actively listen for incoming client connections. After calling the bind() function to associate a
socket with a specific network address (IP address and port number), the listen() function prepares
the socket to accept incoming connections from clients.
Here's the syntax of the listen() function:

#include <sys/socket.h>

int listen(int sockfd, int backlog);

Let's explain each parameter:


 sockfd -
o This is the file descriptor of the socket that you want to set in the listening mode.
o The sockfd should be a valid socket descriptor obtained from a previous call to the
socket() function and a subsequent call to the bind() function.
 backlog -
o The backlog parameter specifies the maximum number of pending client
connections that can be queued up before the server starts rejecting new
connections.
o The backlog parameter allows you to control the size of the connection queue when
the server is busy and cannot handle new incoming connections immediately.
o A typical value for the backlog parameter is often set to 5 or more, depending on
the expected load and the nature of the server application.
After calling listen(), the socket becomes a "passive" socket, waiting for incoming connection
requests. It does not mean that the server is actively handling clients yet; instead, it's ready to
accept connections and queue them up in the connection backlog until the server has the capacity
to process them.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 10
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket – accept( )
In C socket programming, the accept() function is used by a server to accept incoming client
connections. After calling the listen() function to put the server's bound socket into a listening
state, the server can use the accept() function to establish a new socket connection with a client
when the client tries to connect.
Here's the syntax of the accept() function:

#include <sys/types.h>

#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

let's explain each parameter:


 sockfd -
o This is the file descriptor of the listening socket.
o The sockfd should be a valid socket descriptor that has been created using the
socket() function and bound to a local address using the bind() function, and then
put in the listening state using the listen() function.
 addr -
o A pointer to a struct sockaddr that will be filled in by the accept() function with
the client's address information after a successful connection.
o The struct sockaddr is a generic structure used to hold various types of socket
addresses (IPv4, IPv6, Unix domain, etc.).
o To receive the client's address in a specific format (e.g., IPv4 with struct
sockaddr_in), you need to cast the addr pointer appropriately (e.g., (struct
sockaddr*)&client_address).
 addrlen -
o A pointer to a socklen_t variable that specifies the size of the addr structure.
o On input, it indicates the size of the buffer pointed to by addr. On output, it is
updated with the actual size of the client's address information.
o The value of addrlen must be initialized to the size of the buffer pointed to by addr.
The accept() function blocks until an incoming connection request is received. When a client
attempts to connect to the server, the accept() function creates a new socket specifically for that
client and establishes a dedicated communication channel between the server and the client. The
new socket descriptor returned by accept() is the one used for communication with that specific
client.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 11
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

Socket Communications
Socket communication is a fundamental concept in computer networking, allowing processes
running on different devices or computers to exchange data over a network. Sockets provide a
bidirectional communication channel between a client and a server, enabling them to send and
receive data in real-time.
Socket communication typically involves two main protocols: TCP (Transmission Control
Protocol) and UDP (User Datagram Protocol). Each protocol serves different communication
needs:
1. TCP (Transmission Control Protocol):
o TCP is a connection-oriented, reliable, and stream-oriented protocol.
o It ensures that data is delivered accurately and in the correct order. If any data
packets are lost during transmission, TCP automatically retransmits them.
o TCP performs flow control and congestion control to manage the data flow and
prevent network congestion.
o It is ideal for applications where data integrity and reliable delivery are essential,
such as web browsing, email, file transfer (FTP), and database communication.
2. UDP (User Datagram Protocol):
o UDP is a connectionless, unreliable, and datagram-oriented protocol.
o It does not guarantee the delivery or ordering of data packets. If any packets are
lost, there is no automatic retransmission.
o UDP is faster and has lower overhead compared to TCP due to its simplicity and
lack of connection setup.
o It is suitable for applications that prioritize speed and real-time responsiveness over
data reliability, such as video streaming, online gaming, and Voice over IP (VoIP).

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 12
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

The typical steps involved in socket communication are as follows:


1. Socket Creation:
Both the client and server create
sockets using the socket() function.
The client creates a client socket,
while the server creates a server
socket.
2. Binding (Server-side only):
The server binds the server socket
to a specific IP address and port
number using the bind() function.
This allows clients to know where
to connect.
3. Listening (Server-side only):
The server uses the listen() function
to make the server socket ready to
accept incoming client connections.
4. Connection Establishment (Client-side only):
The client uses the connect() function to establish a connection to the server's IP address
and port number.
5. Accepting Connections (Server-side only):
The server uses the accept() function to accept incoming client connections after the clients
attempt to connect.
6. Data Exchange:
Once the connection is established, both the client and server can use the socket to send
and receive data using send() and recv() functions (for TCP) or sendto() and recvfrom()
functions (for UDP).
7. Connection Termination:
When the communication is complete or either party wants to end the connection, they can
close their sockets using the close() function.
Socket communication is widely used for various networked applications, including web
browsing, email, video streaming, online gaming, instant messaging, and more. It provides the
backbone for communication in today's interconnected world.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 13
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

//server.c (Client –Server communication using Sockets)


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCKET_PATH "/tmp/mysocket.sock"


#define BUFFER_SIZE 256

int main() {
int serverSocket, clientSocket;
struct sockaddr_un serverAddress, clientAddress;
char buffer[BUFFER_SIZE];
int bytesReceived;

// Create a server socket


serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
if (serverSocket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}

// Set the server address structure


memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sun_family = AF_UNIX;
strncpy(serverAddress.sun_path, SOCKET_PATH, sizeof(serverAddress.sun_path) - 1);

// Bind the server socket to a file


if (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}

// Listen for client connections


if (listen(serverSocket, 1) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}

printf("Server is running and listening for connections...\n");


// Accept client connections
socklen_t clientAddressLength = sizeof(clientAddress);
clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &clientAddressLength);

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 14
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

if (clientSocket == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("Client connected.\n");

// Receive messages from the client


while ((bytesReceived = recv(clientSocket, buffer, BUFFER_SIZE, 0)) > 0) {
buffer[bytesReceived] = '\0';
printf("Received from client: %s\n", buffer);
}
if (bytesReceived == -1) {
perror("recv");
exit(EXIT_FAILURE);
}
// Close the client socket
close(clientSocket);

// Close the server socket and remove the socket file


close(serverSocket);
unlink(SOCKET_PATH);
return 0;
}

Explanation:
Server Program (server.c) Flow:
1. Create a server socket using the socket() function:
 Arguments:
o AF_UNIX: This specifies that we are creating a Unix domain socket.
o SOCK_STREAM: This specifies that we are creating a stream socket for
reliable, two-way, connection-based communication.
o 0: The protocol, which is 0 for the default protocol based on the socket
types.
 Returns:
o The socket file descriptor (an integer) representing the server socket.
2. Set up the server address structure using memset() and strncpy() functions:
 memset(): This clears the serverAddress structure to ensure there are no garbage
values.
 strncpy(): This copies the SOCKET_PATH constant (which contains the socket file
path) into serverAddress.sun_path.
3. Bind the server socket to a file using the bind() function:
 Arguments:
o serverSocket: The server socket file descriptor.
_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 15
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

o (struct sockaddr*)&serverAddress: A pointer to the server address


structure.
o sizeof(serverAddress): The size of the server address structure.
 The bind() function associates the socket with the specified address (in this case,
the Unix domain socket file path).
4. Listen for incoming client connections using the listen() function:
 Arguments:
o serverSocket: The server socket file descriptor.
o 1: The maximum number of queued connections that can be waiting for
acceptance.
 The listen() function prepares the socket to accept incoming client connections.
5. Accept client connections using the accept() function:
 Arguments:
o serverSocket: The server socket file descriptor.
o (struct sockaddr*)&clientAddress: A pointer to the client address structure.
o &clientAddressLength: A pointer to the length of the client address
structure.
o The accept() function blocks until a client connection is established.
o When a client connects, the function returns a new socket file descriptor
(clientSocket) representing the connection to that client.
6. Receive messages from the client using the recv() function:
 Arguments:
o clientSocket: The client socket file descriptor.
o buffer: A character buffer to store the received data.
o BUFFER_SIZE: The maximum number of bytes to receive at a time.
o 0: Flags, which in this case, is set to 0 (no special flags).
 The recv() function blocks until data is received from the client. It then stores the
received data in the buffer and returns the number of bytes received.
7. Close the client socket and the server socket using the close() function:
 Arguments:
o clientSocket: The client socket file descriptor to be closed.
o serverSocket: The server socket file descriptor to be closed.
 The close() function releases the resources associated with the respective sockets.
8. Unlink (remove) the socket file using the unlink() function:
 Argument:
o SOCKET_PATH: The socket file path.
o The unlink() function removes the socket file from the file system.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 16
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

// Server Program (server.c):


1. Include necessary header files:
 stdio.h: Standard I/O functions (e.g., printf).
 stdlib.h: Standard library functions (e.g., exit).
 string.h: String manipulation functions (e.g., memset, strncpy).
 unistd.h: UNIX standard functions (e.g., close).
 sys/socket.h: Definitions for socket-related functions and structures.
 sys/un.h: Definitions for UNIX domain sockets.
2. Define constants and buffer size:
 SOCKET_PATH: A constant representing the file path for the UNIX domain
socket.
 BUFFER_SIZE: The size of the buffer used for sending and receiving messages.
3. main function:
 Create necessary variables: serverSocket, clientSocket, serverAddress,
clientAddress, buffer, and bytesReceived.
 Create a server socket using socket() and handle errors if the socket creation fails.
 Set up the server address structure using memset() and strncpy().
 Bind the server socket to the specified file using bind().
 Listen for incoming client connections using listen().
 Accept a client connection using accept() and handle errors if the connection fails.
 Receive messages from the client using recv() in a loop until the connection is
closed or an error occurs.
 Display the received messages on the server's console.
 Close the client socket and the server socket using close().
 Unlink (remove) the socket file from the file system using unlink().

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 17
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

//client.c (Client –Server communication using Sockets)


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCKET_PATH "/tmp/mysocket.sock"


#define BUFFER_SIZE 256

int main() {
int clientSocket;
struct sockaddr_un serverAddress;
char buffer[BUFFER_SIZE];
ssize_t bytesSent;

// Create a client socket


clientSocket = socket(AF_UNIX, SOCK_STREAM, 0);
if (clientSocket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}

// Set the server address structure


memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sun_family = AF_UNIX;
strncpy(serverAddress.sun_path, SOCKET_PATH, sizeof(serverAddress.sun_path) - 1);

// Connect to the server


if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}

printf("Connected to the server.\n");

// Send messages to the server


while (1) {
printf("Enter a message (or 'q' to quit): ");
fgets(buffer, BUFFER_SIZE, stdin);
buffer[strcspn(buffer, "\n")] = '\0';

if (strcmp(buffer, "q") == 0) {
break;

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 18
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

bytesSent = send(clientSocket, buffer, strlen(buffer), 0);


if (bytesSent == -1) {
perror("send");
exit(EXIT_FAILURE);
}
}

// Close the client socket


close(clientSocket);

return 0;
}

Explanation:
Client Program (client.c) Flow:
1. Create a client socket using the socket() function (similar to the server).
2. Set up the server address structure using memset() and strncpy() functions (similar to the
server).
3. Connect to the server using the connect() function:
 Arguments:
o clientSocket: The client socket file descriptor.
o (struct sockaddr*)&serverAddress: A pointer to the server address
structure.
o sizeof(serverAddress): The size of the server address structure.
 The connect() function establishes a connection to the server's Unix domain
socket.
4. Send messages to the server using the send() function:
 Arguments:
o clientSocket: The client socket file descriptor.
o buffer: A character buffer containing the message to send.
o strlen(buffer): The length of the message in bytes.
o 0: Flags, which in this case, is set to 0 (no special flags).
 The send() function sends the message in the buffer to the server.
5. Close the client socket using the close() function (similar to the server).
6. Repeat steps 3 to 5 until the user enters 'q' to quit.
Both the client and server programs use the SOCKET_PATH constant, which specifies the file
path for the Unix domain socket. This path should be the same for both the client and the server
so that they can communicate with each other. The client sends messages to the server, and the
server receives and displays these messages.

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 19
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

//Client Program (client.c):


1. Include necessary header files (same as in the server program).
 Define constants and buffer size (same as in the server program).
2. main function:
 Create necessary variables: clientSocket, serverAddress, buffer, and bytesSent.
 Create a client socket using socket() and handle errors if the socket creation fails.
 Set up the server address structure using memset() and strncpy().
 Connect to the server using connect() and handle errors if the connection fails.
 In a loop, prompt the user to enter a message, send it to the server using send(), and
handle errors if the sending fails.
 If the user enters 'q', break the loop and close the client socket using close().

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 20
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

PPT Slides

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 21
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 22
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 23
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 24
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 25
KR21 - B.Tech II Year II Sem CSE (Section B) Unit 5B - Introduction to Sockets | Network IPC
------------------------------------------------------------------------------------------------------------------------------------------

_____________________________________________________________________________________
Dr. Majeti Srinadh Swamy, CSE Dept. Page | 26

You might also like