In C programming, when working with network programming, the sockaddr structure is commonly used to store socket address information, which includes IP address and port number. For IPv4 and IPv6, the C standard library provides different structures: sockaddr_in for IPv4 and sockaddr_in6 for IPv6. To extract the IP address from these structures, you can use library functions such as inet_ntop(), which is a network address conversion function that converts network addresses into dotted-decimal string format.
The following is an example demonstrating how to extract an IP address from a sockaddr structure:
c#include <stdio.h> #include <string.h> #include <arpa/inet.h> int main() { // Create an IPv4 socket address structure struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(8080); inet_pton(AF_INET, "192.168.0.1", &addr.sin_addr); // Buffer to store the converted IP address string char ip_str[INET_ADDRSTRLEN]; // Extract the IP address from the sockaddr_in structure and convert to string format if (inet_ntop(AF_INET, &addr.sin_addr, ip_str, sizeof(ip_str))) { printf("IP address is: %s\n", ip_str); } else { perror("inet_ntop failed"); } return 0; }
In this example:
-
First, define and initialize a
sockaddr_instructure for IPv4 address. -
Use the
inet_pton()function to convert a dotted-decimal IP address into binary form in network byte order and store it insin_addr. -
Call the
inet_ntop()function to extract the IP address fromsin_addrand convert it into a human-readable string format.
For IPv6 addresses, you can use a similar approach but with the sockaddr_in6 structure and appropriate function parameters.
This method ensures code readability and robustness, correctly handling various scenarios including error checking when processing network address conversions.