{"id":3721,"date":"2024-03-06T11:43:31","date_gmt":"2024-03-06T11:43:31","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=3721"},"modified":"2024-03-06T11:43:31","modified_gmt":"2024-03-06T11:43:31","slug":"socket-programming-in-cpp","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/socket-programming-in-cpp\/","title":{"rendered":"Socket Programming In C\/C++"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#socket-programming-in-c-c\">Socket Programming in C\/C++<\/a><\/li><li ><a href=\"#1-socket-creation\">1. Socket creation:<\/a><\/li><li ><a href=\"#2-setsockopt\">2. Setsockopt:<\/a><\/li><li ><a href=\"#3-bind\">3. Bind:<\/a><\/li><li ><a href=\"#4-listen\">4. Listen:<\/a><\/li><li ><a href=\"#5-accept\">5. Accept:<\/a><\/li><li ><a href=\"#stages-for-client\">Stages For Client <\/a><\/li><li ><a href=\"#implementation\">Implementation<\/a><\/li><li ><a href=\"#faq-socket-programming-in-c-c\">FAQ- Socket Programming in C\/C++<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"socket-programming-in-c-c\">Socket Programming in C\/C++<\/h2>\n\n\n\n<p>Socket programming is a method for enabling communication between two nodes on a network. One node, acting as a server, listens on a specific port at an IP address. The other node, functioning as a client, initiates a connection to the server. In this communication setup, the server establishes a listener socket, and the client initiates contact with the server.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-socket-creation\"><strong>1. Socket creation:<\/strong><\/h2>\n\n\n\n<p>In socket programming, the <code>socket<\/code> function is used with the following parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>sockfd<\/code>: Socket descriptor, represented as an integer, similar to a file handle.<\/li>\n\n\n\n<li><code>domain<\/code>: An integer specifying the communication domain. Examples include AF_LOCAL for communication between processes on the same host, AF_INET for processes connected by IPV4, and AF_INET6 for processes connected by IPV6.<\/li>\n\n\n\n<li><code>type<\/code>: Communication type, where <code>SOCK_STREAM<\/code> is used for TCP (reliable and connection-oriented) and <code>SOCK_DGRAM<\/code> is used for UDP (unreliable and connectionless).<\/li>\n\n\n\n<li><code>protocol<\/code>: The protocol value for Internet Protocol (IP), typically set to 0. This value corresponds to the protocol field in the IP header of a packet.<\/li>\n<\/ul>\n\n\n\n<p>For instance, when creating a TCP socket for communication between processes on different hosts connected by IPV4, the <code>socket<\/code> function might be called with parameters like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int sockfd = socket(AF_INET, SOCK_STREAM, 0);<\/code><\/pre>\n\n\n\n<p>This line creates a socket descriptor (<code>sockfd<\/code>) for a TCP socket using the Internet Protocol version 4 (AF_INET) and the reliable, connection-oriented communication type (SOCK_STREAM). The protocol field is set to 0, indicating that the default protocol for the specified domain and type should be used.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-setsockopt\"><strong>2. Setsockopt:<\/strong><\/h2>\n\n\n\n<p>manipulating socket options for the file descriptor <code>sockfd<\/code> is an optional yet valuable practice in socket programming. It allows for the customization of socket behavior, particularly aiding in the reuse of addresses and ports. This is particularly useful in preventing errors such as &#8220;address already in use,&#8221; ensuring smoother execution and better handling of network resources.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int setsockopt(int sockfd, int level, int optname,  const void *optval, socklen_t optlen);\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-bind\"><strong>3. Bind:<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\n\n<\/code><\/pre>\n\n\n\n<p>After making the socket, the &#8220;bind&#8221; function links it to a specific address and port number provided in the &#8220;addr&#8221; (custom data structure). In the example code, we connect the server to the localhost, so we use INADDR_ANY to indicate the IP address.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-listen\"><strong>4. Listen:<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>int listen(int sockfd, int backlog);\n\n<\/code><\/pre>\n\n\n\n<p>a.<strong>passive Mode:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Putting the server socket in passive mode means that the socket is ready to accept incoming connection requests from clients.<\/li>\n\n\n\n<li>This is typically done using the <code>listen<\/code> function in the Berkeley Sockets API.<\/li>\n<\/ul>\n\n\n\n<p>b.<strong>Backlog:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>listen<\/code> function takes a second parameter, which is the backlog. This parameter defines the maximum length of the queue of pending connections for the specified socket (<code>sockfd<\/code>).<\/li>\n\n\n\n<li>The backlog essentially represents the maximum number of clients that can wait to be served by the server.<\/li>\n<\/ul>\n\n\n\n<p>c.<strong>Handling Connection Requests:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>When a client attempts to connect to the server, the server accepts the connection request and establishes a connection.<\/li>\n\n\n\n<li>If the number of pending connection requests in the queue exceeds the backlog value, additional connection requests may be refused.<\/li>\n\n\n\n<li>The client may receive an error with the indication <code>ECONNREFUSED<\/code> if the queue is full.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-accept\"><strong>5. Accept:<\/strong><\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<pre class=\"wp-block-code\"><code>int new_socket= accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);<\/code><\/pre>\n<\/blockquote>\n\n\n\n<p>This process involves accepting the first connection request in the queue for the listening socket (<code>sockfd<\/code>). It creates a new connected socket and returns a file descriptor for that socket. This marks the establishment of a connection between the client and server, ready for data transfer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"stages-for-client\">Stages For Client <\/h2>\n\n\n\n<p>a.<strong>Socket Connection:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The process of creating a socket connection is identical to that of the server&#8217;s socket creation.<\/li>\n\n\n\n<li>It involves using a system call (e.g., <code>socket()<\/code>) to create a socket, specifying the address family, socket type, and protocol.<\/li>\n<\/ul>\n\n\n\n<p>b.<strong>Connect System Call:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>connect()<\/code> system call is used to establish a connection for a socket.<\/li>\n\n\n\n<li>It takes the socket file descriptor (<code>sockfd<\/code>) and the address (<code>addr<\/code>) to which the connection should be made.<\/li>\n\n\n\n<li>In the context of a client connecting to a server, the server&#8217;s address and port are typically specified in <code>addr<\/code>.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"implementation\"><strong>Implementation<\/strong><\/h2>\n\n\n\n<p>One hello message is being exchanged between server and client and this could enable to illustrate the client\/server model.<\/p>\n\n\n\n<p><strong>Server.c<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/ Server side C\/C++ program to demonstrate Socket\n\/\/ programming\n#include &lt;netinet\/in.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys\/socket.h&gt;\n#include &lt;unistd.h&gt;\n#define PORT 8080\nint main(int argc, char const* argv&#91;])\n{\n    int server_fd, new_socket;\n    ssize_t valread;\n    struct sockaddr_in address;\n    int opt = 1;\n    socklen_t addrlen = sizeof(address);\n    char buffer&#91;1024] = { 0 };\n    char* hello = \"Hello from server\";\n \n    \/\/ Creating socket file descriptor\n    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) {\n        perror(\"socket failed\");\n        exit(EXIT_FAILURE);\n    }\n \n    \/\/ Forcefully attaching socket to the port 8080\n    if (setsockopt(server_fd, SOL_SOCKET,\n                   SO_REUSEADDR | SO_REUSEPORT, &amp;opt,\n                   sizeof(opt))) {\n        perror(\"setsockopt\");\n        exit(EXIT_FAILURE);\n    }\naddress.sin_family = AF_INET;\n    address.sin_addr.s_addr = INADDR_ANY;\n    address.sin_port = htons(PORT);\n \n    \/\/ Forcefully attaching socket to the port 8080\n    if (bind(server_fd, (struct sockaddr*)&amp;address,\n             sizeof(address))\n        &lt; 0) {\n        perror(\"bind failed\");\n        exit(EXIT_FAILURE);\n    }\n    if (listen(server_fd, 3) &lt; 0) {\n        perror(\"listen\");\n        exit(EXIT_FAILURE);\n    }\n    if ((new_socket\n         = accept(server_fd, (struct sockaddr*)&amp;address,\n                  &amp;addrlen))\n        &lt; 0) {\n        perror(\"accept\");\n        exit(EXIT_FAILURE);\n    }\n    valread = read(new_socket, buffer,\n                   1024 - 1); \/\/ subtract 1 for the null\n                              \/\/ terminator at the end\n    printf(\"%s\\n\", buffer);\n    send(new_socket, hello, strlen(hello), 0);\n    printf(\"Hello message sent\\n\");\n \n    \/\/ closing the connected socket\n    close(new_socket);\n    \/\/ closing the listening socket\n    close(server_fd);\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p><strong>client.c<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Client side C\/C++ program to demonstrate Socket\n\/\/ programming\n#include &lt;arpa\/inet.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys\/socket.h&gt;\n#include &lt;unistd.h&gt;\n#define PORT 8080\n \nint main(int argc, char const* argv&#91;])\n{\n    int status, valread, client_fd;\n    struct sockaddr_in serv_addr;\n    char* hello = \"Hello from client\";\n    char buffer&#91;1024] = { 0 };\n    if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) {\n        printf(\"\\n Socket creation error \\n\");\n        return -1;\n    }\n \n    serv_addr.sin_family = AF_INET;\n    serv_addr.sin_port = htons(PORT);\n \n    \/\/ Convert IPv4 and IPv6 addresses from text to binary\n    \/\/ form\n    if (inet_pton(AF_INET, \"127.0.0.1\", &amp;serv_addr.sin_addr)\n        &lt;= 0) {\n        printf(\n            \"\\nInvalid address\/ Address not supported \\n\");\n        return -1;\n    }\nif ((status\n         = connect(client_fd, (struct sockaddr*)&amp;serv_addr,\n                   sizeof(serv_addr)))\n        &lt; 0) {\n        printf(\"\\nConnection Failed \\n\");\n        return -1;\n    }\n    send(client_fd, hello, strlen(hello), 0);\n    printf(\"Hello message sent\\n\");\n    valread = read(client_fd, buffer, 1024 - 1); \/\/ subtract 1 for the null terminator at the end\n    printf(\"%s\\n\", buffer);\n \n    \/\/ closing the connected socket\n    close(client_fd);\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Compiling:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>gcc client.c -o client\ngcc server.c -o server<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Client:Hello message sent\nHello from server\nServer:Hello from client\nHello message sent<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-socket-programming-in-c-c\">FAQ- Socket Programming in C\/C++<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1700741195363\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. What is the socket method in C++?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. Sockets facilitate network communication between applications by creating a connection between two endpoints. The <code>socket()<\/code> function, found in languages like C and Python, generates a socket and provides a file descriptor for subsequent referencing. This file descriptor is used to configure and manage communication between devices over the network, with functions like <code>bind()<\/code> and <code>connect()<\/code> being employed for further setup. Finally, the <code>close()<\/code> function is used to terminate the socket when communication is complete.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1700741199101\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2.What is the syntax of a socket?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. The <code>socket()<\/code> function is utilized with the signature <code>int socket(int domain, int type, int protocol)<\/code>. The <code>domain<\/code> parameter determines the communication method, commonly using <code>AF_INET<\/code> for TCP\/IP sockets. The <code>type<\/code> parameter defines the nature of communication.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1700741204383\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. What is socket and its types?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <strong>Datagram Socket:<\/strong> A type of socket that provides a connectionless, message-oriented communication. Datagram sockets are often associated with UDP (User Datagram Protocol).<br \/><strong>Stream Socket:<\/strong> This type of socket offers a connection-oriented, reliable, and stream-oriented communication. Stream sockets are commonly used with TCP (Transmission Control Protocol).<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Socket Programming in C\/C++ Socket programming is a method for enabling communication between two nodes on a network. One node, acting as a server, listens on a specific port at an IP address. The other node, functioning as a client, initiates a connection to the server. In this communication setup, the server establishes a listener &#8230; <a title=\"Socket Programming In C\/C++\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/socket-programming-in-cpp\/\" aria-label=\"More on Socket Programming In C\/C++\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":5464,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[616],"class_list":["post-3721","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-socket-programming-in-c-c","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3721","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=3721"}],"version-history":[{"count":9,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3721\/revisions"}],"predecessor-version":[{"id":7960,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3721\/revisions\/7960"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/5464"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=3721"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=3721"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=3721"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}