How to do socket programming in C/C++?

How to do socket programming in C/C++?

Hello everyone in this article, we are going to study socket programming in C/C++ programming language. First, let’s understand what is socket programming and its applications, and then we will study the different types of functions.

Introduction

What is socket programming?

With the help of socket programming, it is possible to create networked applications that can communicate with one another on the internet using the network sockets that are available. Across a computer network, a network socket is an endpoint for sending and receiving data. Data can be sent and received over a network using socket programming, using standard data structures and functions. 

There are two types of sockets

  1. Client socket: Client sockets are used by a client application in order to connect to the server and send requests to the server
    • Here are some examples of how server sockets might be used in real-life applications. Web browsing: When you use a web browser to access a website, your computer is acting as a client and is sending requests to a server (which is hosting the website). The server then sends back the HTML, CSS, and JavaScript files that make up the website, which your browser then renders for you to view
    • Remote access: Client sockets can be used to establish a remote connection to another computer, allowing you to access files and applications on that computer as if you were sitting in front of it. This is often used in conjunction with remote desktop software, such as TeamViewer or Remote Desktop.
  2. Server socket: A server socket is used by the server to accept incoming connections from clients.
    • Here are some examples of how server sockets might be used in real-life applications. Web servers: When you access a website, your computer sends a request to a web server, which is a computer that stores the website’s files and serves them to clients (such as your web browser) upon request. The web server listens for incoming requests from clients and sends back the appropriate files in response.
    • Mail servers: A mail server is a computer that receives, stores, and sends emails. When you send an email, your computer connects to the mail server and sends the email to it. The mail server then stores the email and sends it to the recipient’s mail server when the recipient checks their email.

Applications of socket programming?

Socket programming is used in many applications, including web servers, online games, and file transfer clients. It is also used to build distributed systems, where multiple programs running on different computers need to communicate with each other. Socket programming is supported by most operating systems. Several programming languages, including C, C++, Java, and Python, can be used to implement. It is a flexible and powerful tool for building networked applications and is widely used in both commercial and open-source software.

Setting up a socket in C/C++

Development Environment for C/C++

If you are already familiar with C/C++ programming then you might have installed the gcc compilers and are able to run your programs. But if you are new to this language we need to install the compilers in order to run functions. To install them check out this article here I have mentioned them clearly. Once you have set up your development environment you can start writing socket programs in C/C++.

Creating a socket with the socket() and bind() function

To create and initialize a socket in C/C++, you will need to use the socket() and bind() functions. Here is an example of how to use these functions:

#include <sys/socket.h>
#include <netinet/in.h>

int main() {
  // Create a socket
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    // Error creating socket
    return 1;
  }

  // Initialize the socket address structure
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(8080);
  addr.sin_addr.s_addr = INADDR_ANY;

  // Bind the socket to the address
  int bind_result = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
  if (bind_result < 0) {
    // Error binding socket
    return 1;
  }

  // Now the socket is created and bound, and ready to be used for network communication
  return 0;
}
Code language: C++ (cpp)

The socket() the function creates a socket and returns a file descriptor that can be used to refer to the socket. The first argument specifies the address family (AF_INET for IPv4, AF_INET6 for IPv6, and AF_UNIX for local communication), the second argument specifies the type of socket (SOCK_STREAM for a streaming socket, SOCK_DGRAM for a datagram socket), and the third argument specifies the protocol (0 for the default protocol for the address family).

The bind() the function assigns a name to the socket. The first argument is the file descriptor of the socket, the second argument is a pointer to a socket address structure, and the third argument is the size of the socket address structure. In the example above, we are using the AF_INET address family, which means we are using an IPv4 address, and we are using the sockaddr_in structure to hold the address. We set the sin_family field AF_INET and the sin_port field to the port number (in network byte order), and the sin_addr field to INADDR_ANY, which means that the socket will accept connections from any local IP address.

listen (), accept() functions

After creating and binding the socket, you can use it for network communication by calling other socket functions such as listen() and accept() (for a server) or connect() (for a client).

listen() the function is used to listen for incoming connections on a socket. It is typically used on a server socket that has been bound to a specific address and port using the bind() function. The listen() the function takes two arguments: the socket descriptor, and the maximum number of connections that can be queued for the socket.

The accept() the function is used to accept incoming connections on a socket. It is typically used on a server socket that has been set up to listen for incoming connections using the listen() function. When a connection is received, accept() it creates a new socket descriptor for the connection and returns the descriptor to the calling process.

// Listen for incoming connections
   listen(sockfd, 5);

// Accept an incoming connection
   int new_sockfd = accept(sockfd, NULL, NULL);Code language: C++ (cpp)

Sending and receiving data through a socket

The send() and recv() functions are used to transmit data through a socket in C. These functions are part of the Berkeley sockets API, which is a standard for network communication in C on Unix-like systems. send() a function used to transmit data from a socket to a remote host. It takes three arguments: the socket descriptor, a pointer to the data to be transmitted, and the length of the data in bytes.

The recv() the function is used to receive data from a socket. It takes four arguments: the socket descriptor, a pointer to a buffer where the received data will be stored, the size of the buffer, and a set of flags that control the behavior of the function. The function returns the number of bytes received, 0 if the remote host closed the connection, or -1 if an error occurred.

Here is an example of how to use the send() and recv() functions in C to transmit a simple message between a client and a server:

// Send a message
const char* message = "Hello, World!";
send(sockfd, message, strlen(message), 0);

// Receive a response
char buffer[1024];
recv(sockfd, buffer, sizeof(buffer), 0);

// Print the response
printf("Received: %s\n", buffer);Code language: C++ (cpp)

Conclusion

Now let’s summarize what we have read

  • Sockets allow applications to send and receive data over a network by creating a connection between two endpoints.
  • The socket() the function creates a socket and returns a file descriptor that can be used to refer to the socket.
  • You can use the listen() function to listen for incoming connections and the accept() function to accept incoming connections from clients in a server application. You can connect to a server using the connect() function in a client application
  • Once a connection is established, you can use the send() and recv() functions to send and receive data over the link.

I encourage you to try out socket programming on your own by building simple client-server applications and experimenting with different socket functions and options. This is a great way to learn more about how network communication works and how to build networked applications. Thank you

Sharing is caring

Did you like what Thrishank wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: