Cnet lab week5_fall2024 (2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

National University of Computer and Emerging Sciences (NUCES) Islamabad

Computer Networks Lab


Spring 2024
Week 06

Socket Programming

Socket
A socket is one endpoint of a two way communication link between two programs running on the network. The
socket mechanism provides a means of inter-process communication (IPC) by establishing named contact points
between which the communication takes place. Like ‘Pipe’ is used to create pipes and sockets are created using
‘socket’ system calls. The socket provides a bidirectional FIFO Communication facility over the network. A
socket connecting to the network is created at each end of the communication. Each socket has a specific address.
This address is composed of an IP address and a port number.
Sockets are generally employed in client server applications. The server creates a socket, attaches it to a network
port address then waits for the client to contact it. The client creates a socket and then attempts to connect to the
server socket. When the connection is established, transfer of data takes place.
Sockets are primarily associated with the Transport layer. The Transport layer is responsible for end-to-end
communication and ensures the reliable delivery of data between applications on different devices. Two key
protocols within the Transport layer are Transmission Control Protocol (TCP) and User Datagram Protocol
(UDP), each serving different communication needs.

Socket Function Calls


1. Socket(): To create a socket
2. Bind(): It’s a socket identification like a telephone number to contact
3. Listen(): Ready to receive a connection
4. Connect(): Ready to act as a sender
National University of Computer and Emerging Sciences (NUCES) Islamabad
5. Accept(): Confirmation, it is like accepting to receive a call from a sender
6. Send(): To send data (write)
7. Recv(): To receive data (read)
8. Close(): To close a connection

Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate with each other. One
socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a
connection. The server forms the listener socket while the client reaches out to the server.

Stages for Server


The server is created using the following steps:
National University of Computer and Emerging Sciences (NUCES) Islamabad
1. Socket Creation
int sockfd = socket(domain, type, protocol)
sockfd: socket descriptor, an integer (like a file handle)
domain: integer, specifies communication domain. The server address includes the address family (AF_INET
for IPv4), IP address (INADDR_ANY for any local address), and port number.
type: communication type
SOCK_STREAM: TCP(reliable, connection-oriented)
SOCK_DGRAM: UDP(unreliable, connectionless)
protocol: Protocol value for Internet Protocol(IP), which is 0. This is the same number that appears on the
protocol field in the IP header of a packet.

2. Bind
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
After the creation of the socket, the bind function binds the socket to the address and port number specified in
addr(custom data structure). In the example code, we bind the server to the localhost, hence we use
INADDR_ANY to specify the IP address.

3. Listen
int listen(int sockfd, int backlog);
It puts the server socket in a passive mode, where it waits for the client to approach the server to make a
connection. The backlog defines the maximum length to which the queue of pending connections for sockfd may
grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of
ECONNREFUSED.

4. Accept
int new_socket= accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
National University of Computer and Emerging Sciences (NUCES) Islamabad
It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates
a new connected socket, and returns a new file descriptor referring to that socket. At this point, the connection is
established between client and server, and they are ready to transfer data.

Stages for Client


1. Socket connection
Exactly the same as that of server’s socket creation

2. Connect:
The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by
addr. Server’s address and port is specified in addr.
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Sample Code:
Server Side
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

int main() {
WSADATA wsaData;
National University of Computer and Emerging Sciences (NUCES) Islamabad
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("Failed to initialize Winsock.\n");
return 1;
}

// create the server socket


int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == INVALID_SOCKET) {
printf("Failed to create socket.\n");
WSACleanup();
return 1;
}

struct sockaddr_in server_address;


server_address.sin_family = AF_INET;
server_address.sin_port = htons(3036);
server_address.sin_addr.s_addr = INADDR_ANY;

// bind the socket


if (bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)) == SOCKET_ERROR) {
printf("Bind failed.\n");
closesocket(server_socket);
WSACleanup();
return 1;
}

listen(server_socket, 5);
printf("Server is listening on port 3036...\n");

// accept a client connection


int client_socket = accept(server_socket, NULL, NULL);
if (client_socket == INVALID_SOCKET) {
printf("Failed to accept connection.\n");
closesocket(server_socket);
WSACleanup();
return 1;
}

// handle communication (e.g., receive a message from the client)


char buffer[200];
National University of Computer and Emerging Sciences (NUCES) Islamabad
recv(client_socket, buffer, sizeof(buffer), 0);
printf("Received message: %s\n", buffer);

// respond to the client


char response[] = "Hello from the server!";
send(client_socket, response, sizeof(response), 0);

closesocket(client_socket);
closesocket(server_socket);
WSACleanup();

return 0;
}

Client Side
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

int main() {
WSADATA wsaData;

// Initialize Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("Failed to initialize Winsock.\n");
return 1;
}

char request[256] = "hello from the client side... !";


char buf[200];

// create the socket


int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
printf("Failed to create socket.\n");
WSACleanup();
National University of Computer and Emerging Sciences (NUCES) Islamabad
return 1;
}

// setup an address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(3036);

// Use localhost (127.0.0.1) for testing, replace with server's IP for real connection
inet_pton(AF_INET, "127.0.0.1", &server_address.sin_addr);

if (connect(sock, (struct sockaddr *) &server_address, sizeof(server_address)) == SOCKET_ERROR) {


printf("Connection failed with error: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}

send(sock, request, sizeof(request), 0);


recv(sock, buf, sizeof(buf), 0);

printf("\n %s \n", buf);

// close the socket


closesocket(sock);

// Cleanup Winsock
WSACleanup();

return 0;
}

How to Run the code?


Open two separate terminals, each accessing the folder you have your code in. Compile both the files using the
command : gcc -o exefilenameTobeassigned filename.c -wls2_32
Once compiled without errors, access the server exe file, and then the client exe file. For reference see the
image attached below.
National University of Computer and Emerging Sciences (NUCES) Islamabad

Practice tasks
Task 1:
Create a simple client-server interaction using socket programming in C. The server should listen for incoming
connections and display messages received from the client. The client, on the other hand, should allow users to
input messages to be sent to the server. Implement a mechanism for the client to signal the end of the conversation,
and ensure that the server reacts accordingly by displaying the messages and terminating the connection. Provide
both the client and server source code along with instructions for running the programs.

Task 2:
Implement a client-server application where the client sends a string to the server, and the server responds with
the reversed version of the string. The client allows the user to input a string. The server processes the string,
reverses it, and sends it back to the client. Display both the sent and received messages on the client side.

Submission Guidelines:
● Source code for both client and server renamed to your roll number.
● Screenshot of the terminal with message transfer.

You might also like