freeaddrinfo - Linux
Overview
freeaddrinfo is a Linux command used to free the linked list of linked addrinfo structures returned by getaddrinfo(3). This command is commonly used as part of network programming in C and C++ to release memory allocated during address resolution.
Syntax
freeaddrinfo(struct addrinfo *res)
Parameters
| Parameter | Description |
|—|—|
| res | Pointer to the linked list of addrinfo structures to be freed. |
Options/Flags
None.
Examples
Simple Usage:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
int main() {
struct addrinfo hints, *res;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int err = getaddrinfo(NULL, "8080", &hints, &res);
if (err != 0) {
perror("getaddrinfo failed");
exit(EXIT_FAILURE);
}
freeaddrinfo(res);
return 0;
}
Advanced Usage:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
int main() {
struct addrinfo hints, *res, *ptr;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET6;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
int err = getaddrinfo("example.com", "8080", &hints, &res);
if (err != 0) {
perror("getaddrinfo failed");
exit(EXIT_FAILURE);
}
ptr = res;
while (ptr != NULL) {
printf("Host: %s\n", ptr->ai_canonname);
printf("Address: %s\n", ptr->ai_addr->sa_data);
ptr = ptr->ai_next;
}
freeaddrinfo(res);
return 0;
}
Common Issues
Memory Leak:
If freeaddrinfo is not called after a successful call to getaddrinfo(3), it can result in a memory leak.
Solution:
Always call freeaddrinfo to release the memory allocated by getaddrinfo(3).
Integration
Combining with getaddrinfo(3):
freeaddrinfo is typically used in conjunction with getaddrinfo(3) to resolve hostnames and IP addresses.
Using with other commands:
freeaddrinfo can be used with other commands that require addrinfo structures, such as bind(2), connect(2), and accept(2).
Related Commands
- getaddrinfo(3)
- getnameinfo(3)
- gai_strerror(3)