C Programming

How to Bind a Socket to a Port in C

A very important part of socket programming in the C language is the binding of a socket to a port. The process of binding a socket allows it to be associated with a specific port number on a specific IP address. This bind connection allows the socket to listen for incoming network connections.

Let us discuss about different methods to bind a socket to a port in C. The facility to bind a socket to a specific port plays a very important role in various network applications such as client-server architectures, web servers and many more. At first, we will explain the use of Socket API to bind a socket to a port. Lastly, we will discuss about the use of “getaddrinfo()” function to bind a socket to a port. By understanding these different approaches, we can understand the required information to bind a socket to a port in the C language.

Use the Socket API to Bind a Socket to a Port

The Socket API provide us with many function and structure for computer network communication. We create a socket using the socket() function. We also bind it to a specific port 7071 using the bind() function.

#include <stdio.h>

#include <stdlib.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h> // we Include the <unistd.h> header for the close function

int main() {

    int soc;
    struct sockaddr_in serverAddress;
    int port = 7071;

    // Create a socket
    soc = socket(AF_INET, SOCK_STREAM, 0);


    if (soc < 0) {

        perror ("Socket creation error");
        exit (EXIT_FAILURE);
    }

    printf ("Socket created! \n");

    // Set up the server address structure
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons (port);

    // Bind the socket to the specified address and port


    if (bind (soc, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) {

       perror ("Binding error");
        exit (EXIT_FAILURE);
    }

    printf ("Socket binding successful \n");

    // Close the socket
    close (soc);

    return 0;


}

Output:

$ gcc server.c

$ ./a.out

Socket created!

Socket binding successful

The socket() function is used to create a socket in this programming example. It initialises the “serverAddress” structure with the machine’s port number which is 7071 and its IP address. Using the bind() function, it attaches the socket to the supplied address and port number. This method handles any bind errors and prints the appropriate messages. If the bind succeeds, a confirmation message is printed.

Use the Getaddrinfo() Function to Bind a Socket to a Port

Here, we use the getaddrinfo() function to dynamically receive the address and port information. Then, we bind the socket to any available port. This method of binding helps us to select an available port without mentioning it.

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

int main() {

    int soc;
    struct addrinfo hints, *serverAddress;
    int status;

    // Initialize hints structure
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET; // Use IPv4
    hints.ai_socktype = SOCK_STREAM; // Use TCP

    // Retrieve address information
    if ((status = getaddrinfo(NULL, NULL, &hints, &serverAddress)) != 0) {
        fprintf (stderr, "getaddrinfo error: %s\n", gai_strerror(status));
        exit (EXIT_FAILURE);
    }

    // Iterate through address structures


    for (struct addrinfo* addr = serverAddress; addr != NULL; addr = addr->ai_next) {

        // Create a socket

        soc = socket (addr->ai_family, addr->ai_socktype, addr->ai_protocol);

        if (soc == -1) {
            perror ("Socket creation error");
            continue;
        }

        // Bind the socket


        if (bind (soc, addr->ai_addr, addr->ai_addrlen) == -1) {

           perror ("Binding error");
            close (soc);
            continue;
        }

        // Successful bind, exit the loop
        break;
    }

    // Check if a valid socket descriptor is obtained
    if (soc == -1) {
        fprintf(stderr, "Failed to bind socket\n");
        exit (EXIT_FAILURE);
    }

    printf ("Socket binding successful \n");

    // Clean up
    freeaddrinfo (serverAddress);
    close (soc);
    return 0;


}

Output:

$ gcc server.c

$ ./a.out

Socket binding successful

This programming example makes use of the getaddrinfo() function to dynamically extract the address information based on the supplied hints. It loops over the linked list of address structures until the bind operation is successful. The programme creates a socket and attempts to bind it using the address information it acquired. If the bind operation fails, the procedure moves on to the next address structure. When a successful bind is obtained, the programme comes out from the loop. The program then prints a confirmation message, frees the reserved memory for address information, and closes the connection.

Conclusion

Here, in this article, we understand that the process to bind a socket to a port is very important for socket programming. We discussed about two different methods to bind a socket to a port in the C programming language. At first, we used the Socket API to bind a socket. After that, we explained about the “getaddrinfo()” function to bind a socket. By understanding these approaches, we can easily enable the communication in our network applications. We can choose the specific approach according to our requirements. The binding of socket to a port is very important as it help us to create the client-server based architectures and also help us to create the web servers.

About the author

Bamdeb Ghosh

Bamdeb Ghosh is having hands-on experience in Wireless networking domain.He's an expert in Wireshark capture analysis on Wireless or Wired Networking along with knowledge of Android, Bluetooth, Linux commands and python. Follow his site: wifisharks.com