C Programming

C: getsockname Function Usage

Socket programming is well-known and common in C programming between developers and users. Within this kind of programming, we tend to connect two endpoints. These endpoints can be two servers, one server, one socket, etc. As the name suggests, the “getsockname” function is utilized to get the name of a socket working in the network. It may or may not be the socket name, but the address of that particular socket would be displayed using this function. Therefore, we have tried a simple method to illustrate the getsockname() function in C within this guide. Let’s take a fresh look at its example while working on the program using Ubuntu 20.04 Linux system.

Example: GetSockName Function

Let’s take a look at the example of the getsockname function in C. Make use of the “Ctrl+Alt+T” key shortcut to quickly open up the command-line application on your screen. It may take only 10 seconds, and your terminal will be ready for use. Within the terminal instruction area, you have to type the “touch” query along with the “filename” to generate a whole new file in your system, i.e., empty. Many options are available to open this newly generated file, i.e., vim, nano, or text editor. Users may prefer to open it within the text editor first, create a code, update or modify the code, and then execute within the shell. That could be done by simply double-tapping on the file name residing in the file explorer’s “home” folder. If users want to open the empty file within the “GNU Nano” editor, they can utilize the terminal “nano” command. Write this instruction and hit Enter to execute it. Both the instructions for file creation and opening are listed:

The C code starts with the inclusion of some of the main and important header files. The keyword “include” is used with the hash sign to do so. A total of 11 headers are used here. The “stdio.h” has been used to get the standard input and output. The “unistd.h”. is utilized to access the API of the POSIX operating system, i.e., Linux and Unix-like systems. The “stdlib.h” header is a standard library for general purposes, i.e., type conversions, process management, storage allocations, etc. The “errno.h” is mainly used for error problems and reporting. The “string.h” module for C is used to handle the strings along with some of the other functions. The “sys/types.h” header is utilized to define the data types of the variables and the functions used in our program code.

The header file “sys/stat.h” is used here to describe the construction of the information data returned. The header library “sys/socket.h” will be utilized to use the functions and mutable of sockets in our code. The “sys/un.h” header library is here to save the addresses of Unix-like sockets. The “netint/in.h” is specifically designed to initialize the mutable structure type for the IPv6 address in loopback.

The INET ADDRSTRLEN or INET6 ADDRSTRLEN variables usually are defined in the “arpa/inet.h” header library. After all the header files, we have implemented a user-defined function named “ShowError”, taking one argument of constant character pointer “e”. This pointer argument references some errors found so far in our code. For C programming Language, the POSIX error method, i.e., perror, is being used to display an error response message to “stderr” depending on an errno error condition. It outputs “str” and an error response message conforming to the universal mutable errno, as determined by the program code. The “perror” function uses the argument “e” as an error message to show it. The “exit(1)” function is here to exit or end the “ShowError()” function right at the moment:

Here comes the “sock_addr” function of the pointer type taking three arguments in its parameters. The parameter “s” represents the socket, and the character type pointer variable “buf” will be used to store the socket data in it. While the last argument “bufsize” of an object “size_t” type will be used to define the size of a buffer variable or simply buffer. Within this function, we have created a structure named “addr” to store the socket address. The length of the “addr” variable has been stored within the integer type variable “len” by applying the “sizeof” function on it.

The getsockname() function has been utilized here to acquire the name of a socket. This function uses the socket, socket addresses, and socket length as input arguments. Whatever the response is for the getsockname function, the response will be stored in the variable “z”, i.e., collected or not. The “if” statement is here to check the condition that the variable “z” received the return status code as -1, i.e., false. It means, if you find yourself unable to get the name of a socket, it will return NULL to the calling function. The “snprintf” function is used to get the socket’s address, convert it to string form, and display it on the shell. For this, buffer and buffer size must be used as an argument. The address of the socket port is utilized in the function “ntohs” to convert it to host byte code:

The main() function takes 4 arguments in its parameter. The structure type address variable “addr” for a socket is declared with the character type variable “buf” of size 64. Then, we have been creating an internet socket Ipv4 using the socket function. This socket status returns the code and it will be saved to the variable “sck_inet”. If the socket doesn’t create successfully, such as the sck_inet is not equal to zero, it will call the “ShowError” message while passing it a simple text “Socket()”.

After this, we have tried to create an “AF_INET” address. The memset() function is used to initialize the address for a socket to 0. The socket address family has been initialized as “AF_INET”, its port is also declared while the htons function is here to translate the host byte format to network byte format. The inet_aton function utilizes the local IP address to convert it into the standard string format and save it to the socket address variable. The size of the address variable is stored in the “len” variable. The bind() function binds the address to the socket and saves the status return code in “z”. If the status code is “-1”, i.e., false, it will call the “ShowError” message while calling the bind() function in it. If the “sock_addr()” function is unable to be called, it will also call the “ShowError” function taking “sock_addr” as an argument. The printf statement shows the name stored in a buffer:

The close function is called to close the Ipv4 internet socket:

After the compilation and execution, we have the socket name on which our system is connected:


This article is indeed a need for every C user eagerly searching for the example of “getsockname” in Linux. We have discussed a single example in this guide. We have tried to simplify for our users as the code has been divided into chunks. We are hopeful that you will find this article very helpful. Check out other Linux Hint articles for more tips and tutorials.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.