introduction to programming in c++ with sockets
DESCRIPTION
Introduction to Programming in C++ with Sockets. Under Linux operating system. What is a socket?. It is an abstraction that is provided to an application programmer to send or receive data to another process . - PowerPoint PPT PresentationTRANSCRIPT
Introduction to Programming in C++ with Sockets
Under Linux operating system
What is a socket?• It is an abstraction that is provided to
an application programmer to send or receive data to another process.
• Data can be sent to or received from another process running on the same machine or a different machine.
• To build any Networked Application.
Network Programming“Telephone Analogy”
A telephone call over a “telephony network” works as follows:
• Both parties have a telephone installed.• A phone number is assigned to each telephone.• Caller lifts telephone and dials a number. • Turn on ringer to listen for a caller. • Telephone rings and the receiver of the call picks it
up.• Both Parties talk and exchange data.• After conversation is over they hang up the phone.
Dissecting the Analogy
A network application works as follows:
• An endpoint (telephone) for communication is created on both ends.
• An address (phone no) is assigned to both ends to distinguish them from the rest of the network.
• One of the endpoints (caller) initiate a connection to the other.• The other end (receiver) point waits for the communication to
start.• Once a connection has been made, data is exchanged (talk).• Once data has been exchanged the endpoints are closed (hang
up).
In the world of sockets…• Socket() – Endpoint for communication.• Bind() - Assign a unique telephone number.• Listen() – Wait for a caller.• Connect() - Dial a number.• Accept() – Receive a call.• Send(), Recv() – Talk.• Close() – Hang up.
The Client – Server model
• Server – An entity which is a provider of information.
• Client – An entity which is a seeker of information.
• In the socket programming world almost all communication is based on the Client-Server model.
• The Server starts up first and waits for a client to connect to it. After a client successfully connects, it requests some information. The Server serves this information to the client. The client then disconnects and the Server waits for more clients.
A TCP Server – Client Interaction
A UDP Server – Client Interaction
Diving Deeper into the syscalls)(We will now describe the following calls in detail :
• Socket()• Bind()• Listen()• Accept()• Connect()• Read() / Send() / Sendto()• Write() / Recv() / Recvfrom()• Close()
Socket() – A Connection Endpoint
• This creates an endpoint for a network connection.•
Int Socket(int domain, int type, int protocol)
• When a socket is created, the program has to specify the address domain and the socket type.
• Two processes can communicate with each other only if their sockets are of the same type and in the same domain.
• There are two widely used address domains:1-Unix domain.2-Internet domain.• domain = AF_UNIX or AF_INET
Socket() – A Connection Endpoint
• There are two type of socket:1- Stream sockets:- Stream sockets treat communications as a continuous stream of characters.- Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented protocol.
2- Datagram sockets:- read entire messages at once.- datagram sockets use UDP (Unix Datagram Protocol), which is
unreliable and message oriented.
- Type = SOCK_STREAM (TCP) or SOCK_DGRAM (UDP).
Socket() – A Connection Endpoint
•protocol = 0
• (the operating system will choose the most appropriate protocol. It will choose TCP for stream sockets and UDP for datagram sockets)
• Example : socket(PF_INET, SOCK_STREAM, 0);This will create a TCP socket.
• The call returns a socket descriptor on success and -1 on an error.
Bind() – Attaching to an IP and Port
• A server process calls bind to attach itself to a specific port and IP address.
• bind() assigns a name to an unnamed socket. When a socket is created with socket(2) it exists in a name space (address family) but has no name assigned. bind() requests that the name pointed to by name be assigned to the socket.
Int Bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen)
sockfd = socket descriptor returned by socket()
my_addr = pointer to a valid sockaddr_in structure cast as a sockaddr * pointer
addrlen = length of the sockaddr_in structure
Listen() – Wait for a connection• The server process calls listen to tell the kernel to initialize a wait
queue of connections for this socket.
Int Listen(int sock, int backlog)
sock = socket returned by socket()backlog = Maximum length of the pending connections queue
• Example: Listen(sock, 10);This will allow a maximum of 10 connections to be in pending state.
Accept() – A new connection! • Accept is called by a Server process to accept new connections
from new clients trying to connect to the server.
Int Accept(int socket, (struct sockaddr *)&client, socklen_t *client_len)
socket = the socket in listen stateclient = will hold the new client’s information when accept returnsclient_len = pointer to size of the client structure
• Example :
struct sockaddr_in client;
int len = sizeof(client);
Accept(sock, (struct sockaddr *)&client, &len);
Accept() – A new connection! • The server process calls listen to tell the kernel to initialize a wait
queue of connections for this socket.
Int Listen(int sock, int backlog)
sock = socket returned by socket()backlog = Maximum length of the pending connections queue
• Example: Listen(sock, 10);This will allow a maximum of 10 connections to be in pending state.
Connect() – connect to a service• Connect is called by a client to connect to a server port.
Int Connect(int sock, (struct sockaddr *)&server_addr, socklen_t len)
sock: a socket returned by socket()server_addr: a sockaddr_in struct pointer filled with all the remote server details and cast as a sockaddr struct pointerlen: size of the server_addr struct
• Example:
connect(sock, (struct sockaddr *)server_addr, len);
Send / Recv – Finally Data!! • Send(), Recv() , Read() , Write() etc calls are used to send and receive data .
Int send(int sock, void *mesg, size_t len, int flags)
Int recv(int sock, void *mesg, size_t len, int flags)
sock = A connected socketmesg = Pointer to a buffer to send/receive data from/in .len = Size of the message bufferflags = 0
The return value is the number of bytes actually sent/received.
• Example:char send_buffer[1024];char recv_buffer[1024];int sent_bytes;int recvd_bytes;
sent_bytes = send(sock, send_buffer, 1024, 0);recvd_bytes = recv(sock, recv_buffer, 1024, 0);
Close() – Bye ..Bye ! • Close signals the end of communication between a server-client
pair. This effectively closes the socket.
Int close(int sock)
sock = the socket to close
• Example :
close(sock);
A TCP client in C• Client setup:
#include <stdio.h>#include <sys/socket.h>#include <arpa/inet.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <netinet/in.h>#define BUFFSIZE 32void Die(char *mess) { perror(mess); exit(1); }
A TCP client in C• Creating the socket:
int main(int argc, char *argv[]){ int sock;struct sockaddr_in echoserver;char buffer[BUFFSIZE];unsigned int echolen;int received = 0;if (argc != 4){
fprintf(stderr, "USAGE: TCPecho <server_ip> <word> <port>\n");exit(1);
} */Create the TCP socket/*
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ Die("Failed to create socket");
}
A TCP client in C• establish connection:
*/Construct the server sockaddr_in structure/* memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct/* echoserver.sin_family = AF_INET; /* Internet/IP/* echoserver.sin_addr.s_addr = inet_addr(argv[1]); /* IP address/* echoserver.sin_port = htons(atoi(argv[3])); /* server port/*
*/Establish connection/* if (connect(sock,
(struct sockaddr )* &echoserver,sizeof(echoserver)) < 0{ )
Die("Failed to connect with server");}
A TCP client in C• send/receive data:
*/Send the word to the server/* echolen = strlen(argv[2]);if (send(sock, argv[2], echolen, 0) != echolen){
Die("Mismatch in number of sent bytes");}
*/Receive the word back from the server/* fprintf(stdout, "Received: ");while (received < echolen){
int bytes = 0;if ((bytes = recv(sock, buffer, BUFFSIZE-1, 0)) < 1){
Die("Failed to receive bytes from server");}received += bytes;
buffer[bytes] = '\0'; /* Assure null terminated string/* fprintf(stdout, buffer);
}}
A TCP client in C• Wrapup:
fprintf(stdout, "\n");close(sock);exit(0);
}
A TCP server in C• Server setup:
#include <stdio.h>#include <sys/socket.h>
#include <arpa/inet.h>#include <stdlib.h>#include <string.h>#include <unistd.h>
#include <netinet/in.h>#define MAXPENDING 5 /* Max connection requests/*
#define BUFFSIZE 32void Die(char *mess) { perror(mess); exit(1); }
A TCP server in C• the connection:
void HandleClient(int sock){ char buffer[BUFFSIZE];int received = -1;
*/Receive message/* if ((received = recv(sock, buffer, BUFFSIZE, 0)) < 0){
Die("Failed to receive initial bytes from client");}
*/Send bytes and check for more incoming data in loop/* while (received > 0){
*/Send back received data/* if (send(sock, buffer, received, 0) != received){
Die("Failed to send bytes to client");}
*/Check for more data/* if ((received = recv(sock, buffer, BUFFSIZE, 0)) < 0){
Die("Failed to receive additional bytes from client");}}close(sock);
}
A TCP server in C• Configuring the server socket:
int main(int argc, char *argv[]){ int serversock, clientsock;struct sockaddr_in echoserver, echoclient;if (argc != 2){
fprintf(stderr, "USAGE: echoserver <port>\n");exit(1);
} */Create the TCP socket/*
if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ Die("Failed to create socket");
} */Construct the server sockaddr_in structure/*
memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct/* echoserver.sin_family = AF_INET; /* Internet/IP/* echoserver.sin_addr.s_addr = htonl(INADDR_ANY); /* Incoming addr/* echoserver.sin_port = htons(atoi(argv[1])); /* server port/*
A TCP server in C• binding and listening:
*/Bind the server socket/* if (bind(serversock, (struct sockaddr *) &echoserver,
sizeof(echoserver)) < 0{ )Die("Failed to bind the server socket");
} */Listen on the server socket/*
if (listen(serversock, MAXPENDING) < 0){ Die("Failed to listen on server socket");
}
A TCP server in C• socket factory:
*/Run until cancelled/* while (1){
unsigned int clientlen = sizeof(echoclient); */Wait for client connection/*
if ((clientsock= accept(serversock, (struct sockaddr *) &echoclient,
&clientlen)) < 0{ )Die("Failed to accept client connection");
}fprintf(stdout, "Client connected: %s\n,"inet_ntoa(echoclient.sin_addr);)
HandleClient(clientsock);}}
A UDP client in C• Client setup:
#include <stdio.h>#include <sys/socket.h>#include <arpa/inet.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <netinet/in.h>#define BUFFSIZE 255void Die(char *mess) { perror(mess); exit(1); }
A UDP client in C• Declarations and usage message:
int main(int argc, char *argv[]) {int sock;struct sockaddr_in echoserver;struct sockaddr_in echoclient;char buffer[BUFFSIZE];unsigned int echolen, clientlen;int received = 0;if (argc != 4) {fprintf(stderr, "USAGE: %s <server_ip> <word> <port>\n", argv[0]);exit(1);{
A UDP client in C• Create the socket and configure the server structure:
/* Create the UDP socket */if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {Die("Failed to create socket");}/* Construct the server sockaddr_in structure */memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct */echoserver.sin_family = AF_INET; /* Internet/IP */echoserver.sin_addr.s_addr = inet_addr(argv[1]); /* IP address */echoserver.sin_port = htons(atoi(argv[3])); /* server port */
A UDP client in C• Send the message to the server:
/* Send the word to the server */echolen = strlen(argv[2]);if (sendto(sock, argv[2], echolen, 0,(struct sockaddr *) &echoserver,sizeof(echoserver)) != echolen) {Die("Mismatch in number of sent bytes");}
A UDP client in C• Receive the message back from the server:
/* Receive the word back from the server */fprintf(stdout, "Received: ");clientlen = sizeof(echoclient);if ((received = recvfrom(sock, buffer, BUFFSIZE, 0,(struct sockaddr *) &echoclient,&clientlen)) != echolen) {Die("Mismatch in number of received bytes");}/* Check that client and server are using same socket */if (echoserver.sin_addr.s_addr != echoclient.sin_addr.s_addr) {Die("Received a packet from an unexpected server");}buffer[received] = '\0'; /* Assure null-terminated string */fprintf(stdout, buffer);fprintf(stdout, "\n");close(sock);exit(0);}
UDP server in C• Server setup:
#include <stdio.h>#include <sys/socket.h>#include <arpa/inet.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <netinet/in.h>#define BUFFSIZE 255void Die(char *mess) { perror(mess); exit(1); }
UDP server in C• Declarations and usage message:
int main(int argc, char *argv[]){ int sock;struct sockaddr_in echoserver;struct sockaddr_in echoclient;char buffer[BUFFSIZE];unsigned int echolen, clientlen, serverlen;int received = 0;if (argc != 2){
fprintf(stderr, "USAGE: %s <port>\n", argv[0]);exit(1);
}
UDP server in C• Create, configure, and bind the server socket:
/* Create the UDP socket */if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {Die("Failed to create socket");}/* Construct the server sockaddr_in structure */memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct */echoserver.sin_family = AF_INET; /* Internet/IP */echoserver.sin_addr.s_addr = htonl(INADDR_ANY); /* Any IP address */echoserver.sin_port = htons(atoi(argv[1])); /* server port *//* Bind the socket */serverlen = sizeof(echoserver);if (bind(sock, (struct sockaddr *) &echoserver, serverlen) < 0) {Die("Failed to bind server socket");}
UDP server in C• The receive/send loop:
/* Run until cancelled */while (1) {/* Receive a message from the client */clientlen = sizeof(echoclient);if ((received = recvfrom(sock, buffer, BUFFSIZE, 0,(struct sockaddr *) &echoclient,&clientlen)) < 0) {Die("Failed to receive message");}fprintf(stderr,"Client connected: %s\n", inet_ntoa(echoclient.sin_addr));/* Send the message back to client */if (sendto(sock, buffer, received, 0,(struct sockaddr *) &echoclient,sizeof(echoclient)) != received) {Die("Mismatch in number of echo'd bytes");}}}
References
• http://www.linuxhowtos.org/C_C++/socket.htm• http://
ebookbrowse.com/introduction-to-socket-programming-ppt-d143245813
• Programming Linux sockets Using TCP/IP: Creating an echo server and client, Skill Level: Introductory, David Mertz, Ph.D.