1 / 39

Introduction to Programming in C++ with Sockets

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 .

zizi
Download Presentation

Introduction to Programming in C++ with Sockets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programming in C++ with Sockets Under Linux operating system

  2. 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.

  3. 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.

  4. 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).

  5. 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.

  6. 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.

  7. A TCP Server – Client Interaction

  8. A UDP Server – Client Interaction

  9. 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()

  10. 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

  11. 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).

  12. 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.

  13. 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(intsockfd, structsockaddr *my_addr, socklen_taddrlen)sockfd = socket descriptor returned by socket()my_addr = pointer to a valid sockaddr_in structure cast as a sockaddr * pointeraddrlen = length of the sockaddr_in structure

  14. 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.

  15. 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, (structsockaddr *)&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 : structsockaddr_in client;intlen = sizeof(client);Accept(sock, (structsockaddr *)&client, &len);

  16. 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.

  17. Connect() – connect to a service • Connect is called by a client to connect to a server port.Int Connect(int sock, (structsockaddr *)&server_addr, socklen_tlen)sock: a socket returned by socket()server_addr: a sockaddr_instruct pointer filled with all the remote server details and cast as a sockaddrstruct pointerlen: size of the server_addrstruct • Example:connect(sock, (structsockaddr *)server_addr, len);

  18. Send / Recv – Finally Data !! • Send(), Recv() , Read() , Write() etc calls are used to send and receive data .Int send(int sock, void *mesg, size_tlen, int flags)Intrecv(int sock, void *mesg, size_tlen, int flags)sock = A connected socketmesg = Pointer to a buffer to send/receive data from/in .len = Size of the message bufferflags = 0The return value is the number of bytes actually sent/received. • Example:char send_buffer[1024];char recv_buffer[1024];intsent_bytes;intrecvd_bytes;sent_bytes = send(sock, send_buffer, 1024, 0);recvd_bytes = recv(sock, recv_buffer, 1024, 0);

  19. 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);

  20. A TCP client in C #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 32 void Die(char *mess) { perror(mess); exit(1); } Client setup:

  21. A TCP client in C int main(intargc, char *argv[]) { int sock; structsockaddr_inechoserver; char buffer[BUFFSIZE]; unsigned intecholen; 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"); } Creating the socket:

  22. A TCP client in C /* 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, (structsockaddr *) &echoserver, sizeof(echoserver)) < 0) { Die("Failed to connect with server"); } establish connection:

  23. A TCP client in C /* 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); }} send/receive data:

  24. A TCP client in C fprintf(stdout, "\n"); close(sock); exit(0); } Wrapup:

  25. A TCP server in C #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 32 void Die(char *mess) { perror(mess); exit(1); } Server setup:

  26. A TCP server in C 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); } the connection:

  27. A TCP server in C int main(intargc, char *argv[]) { intserversock, clientsock; structsockaddr_inechoserver, 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 */ Configuring the server socket:

  28. A TCP server in C /* Bind the server socket */ if (bind(serversock, (structsockaddr *) &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"); } binding and listening:

  29. A TCP server in C /* Run until cancelled */ while (1) { unsigned intclientlen = sizeof(echoclient); /* Wait for client connection */ if ((clientsock = accept(serversock, (structsockaddr *) &echoclient, &clientlen)) < 0) { Die("Failed to accept client connection"); } fprintf(stdout, "Client connected: %s\n", inet_ntoa(echoclient.sin_addr)); HandleClient(clientsock); } } socket factory:

  30. A UDP client in C #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 255 void Die(char *mess) { perror(mess); exit(1); } Client setup:

  31. A UDP client in C int main(intargc, char *argv[]) { int sock; structsockaddr_inechoserver; structsockaddr_inechoclient; char buffer[BUFFSIZE]; unsigned intecholen, clientlen; int received = 0; if (argc != 4) { fprintf(stderr, "USAGE: %s <server_ip> <word> <port>\n", argv[0]); exit(1);{ Declarations and usage message:

  32. A UDP client in C /* 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 */ Create the socket and configure the server structure:

  33. A UDP client in C /* Send the word to the server */ echolen = strlen(argv[2]); if (sendto(sock, argv[2], echolen, 0, (structsockaddr *) &echoserver, sizeof(echoserver)) != echolen) { Die("Mismatch in number of sent bytes"); } Send the message to the server:

  34. A UDP client in C /* Receive the word back from the server */ fprintf(stdout, "Received: "); clientlen = sizeof(echoclient); if ((received = recvfrom(sock, buffer, BUFFSIZE, 0, (structsockaddr *) &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); } Receive the message back from the server:

  35. UDP server in C #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 255 void Die(char *mess) { perror(mess); exit(1); } Server setup:

  36. UDP server in C int main(intargc, char *argv[]) { int sock; structsockaddr_inechoserver; structsockaddr_inechoclient; char buffer[BUFFSIZE]; unsigned intecholen, clientlen, serverlen; int received = 0; if (argc != 2) { fprintf(stderr, "USAGE: %s <port>\n", argv[0]); exit(1); } Declarations and usage message:

  37. UDP server in C /* 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, (structsockaddr *) &echoserver, serverlen) < 0) { Die("Failed to bind server socket"); } Create, configure, and bind the server socket:

  38. UDP server in C /* Run until cancelled */ while (1) { /* Receive a message from the client */ clientlen = sizeof(echoclient); if ((received = recvfrom(sock, buffer, BUFFSIZE, 0, (structsockaddr *) &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, (structsockaddr *) &echoclient, sizeof(echoclient)) != received) { Die("Mismatch in number of echo'd bytes"); } } } The receive/send loop:

  39. 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.

More Related