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

Computer Networks Lab week4

The document provides an overview of socket programming, detailing the creation and management of sockets for client-server communication in C. It outlines the essential socket function calls and the stages for both server and client setup, including sample code for implementation. Additionally, it includes practice tasks for students to enhance their understanding of socket interactions and submission guidelines for their work.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Computer Networks Lab week4

The document provides an overview of socket programming, detailing the creation and management of sockets for client-server communication in C. It outlines the essential socket function calls and the stages for both server and client setup, including sample code for implementation. Additionally, it includes practice tasks for students to enhance their understanding of socket interactions and submission guidelines for their work.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

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>

#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib

int main() {
WSADATA wsa;
SOCKET server_socket, client_socket;
National University of Computer and Emerging Sciences (NUCES) Islamabad
struct sockaddr_in server_addr, client_addr;
int client_addr_len = sizeof(client_addr);
char server_message[] = "Hi, Yes you have reached the server!";
char buf[200];

// Initialize Winsock
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}

// Create socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == INVALID_SOCKET) {
printf("Could not create socket: %d", WSAGetLastError());
WSACleanup();
return 1;
}

// Prepare the sockaddr_in structure


server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(3001);

// Bind
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
closesocket(server_socket);
WSACleanup();
return 1;
}

// Listen
if (listen(server_socket, 3) == SOCKET_ERROR) {
printf("Listen failed with error code : %d", WSAGetLastError());
closesocket(server_socket);
WSACleanup();
return 1;
}
National University of Computer and Emerging Sciences (NUCES) Islamabad
// Accept and incoming connection
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket == INVALID_SOCKET) {
printf("Accept failed with error code : %d", WSAGetLastError());
closesocket(server_socket);
WSACleanup();
return 1;
}

// Receive data from client


recv(client_socket, buf, sizeof(buf), 0);
printf("\n %s \n", buf);

// Send response
send(client_socket, server_message, sizeof(server_message), 0);

// Cleanup
closesocket(client_socket);
closesocket(server_socket);
WSACleanup();

return 0;
}

Client Side
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // For memset and strlen
#include <winsock2.h> // For Winsock functions and types
#include <ws2tcpip.h> // For getaddrinfo()

#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib

int main() {
WSADATA wsa;
SOCKET sock;
National University of Computer and Emerging Sciences (NUCES) Islamabad
struct sockaddr_in server_address;
char request[256] = "Hello from the client side... !";
char buf[200];
int result;

// Initialize Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed to initialize Winsock. Error code: %d\n", WSAGetLastError());
return 1;
}

// Create the socket


sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
printf("Socket creation failed. Error code: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}

// Setup the server address


memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(3001);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); // Use specific server IP address

// Connect to the server


if (connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) == SOCKET_ERROR) {
printf("Connection failed. Error code: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}

// Send data
if (send(sock, request, strlen(request), 0) == SOCKET_ERROR) {
printf("Send failed. Error code: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
National University of Computer and Emerging Sciences (NUCES) Islamabad

// Receive data
int recv_len = recv(sock, buf, sizeof(buf) - 1, 0);
if (recv_len == SOCKET_ERROR) {
printf("Receive failed. Error code: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}

// Null-terminate the received data and print it


buf[recv_len] = '\0';
printf("\n%s\n", buf);

// Cleanup
closesocket(sock);
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 -lws2_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:
Create a client-server interaction using socket programming in C. In this task:
Server:
• The server should listen on a specific port for incoming connections.
• Upon receiving a connection, the server should display messages sent by the client.
• The server should also be capable of responding with a predefined acknowledgment message after each
received message.
• The server should terminate when it receives a specific "shutdown" command from the client.
Client:
• The client should connect to the server on the specified port.
• The client should allow users to input messages to be sent to the server.
• After sending each message, the client should wait to receive and display the server's acknowledgment.
• The client should allow the user to send a specific "shutdown" command to terminate the server.
National University of Computer and Emerging Sciences (NUCES) Islamabad

Submission Guidelines:
● Source code for both client and server
● Screenshot of the terminal with message transfer.

You might also like