Computer Networks Lab week4
Computer Networks Lab week4
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 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.
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.
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>
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;
}
// 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;
}
// 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()
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;
}
// 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;
}
// Cleanup
closesocket(sock);
WSACleanup();
return 0;
}
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.