IN_ADDR Structure#include <winsock2.h>
struct in_addr {
union {
struct {
u_char s_b1, s_b2, s_b3, s_b4;
} S_un_b;
struct {
u_short s_w1, s_w2;
} S_un_w;
u_long S_addr;
} S_un;
};
The in_addr structure stores an IPv4 address.
The structure contains a union with the following members:
S_unA union that can hold the IPv4 address in different formats.
S_un.S_un_b: A structure containing the address as four u_char (byte) elements.S_un.S_un_w: A structure containing the address as two u_short (word) elements.S_un.S_addr: A u_long that holds the entire IPv4 address as a single 32-bit value in network byte order. This is the most commonly used member.The IN_ADDR structure is used by Winsock functions to represent IPv4 addresses. When you work with IPv4 addresses, you'll typically interact with this structure.
The S_addr member is the preferred way to store and manipulate IPv4 addresses within the structure. It represents the address in network byte order (big-endian).
Here's a basic example of how to use IN_ADDR to represent an IP address:
#include <winsock2.h>
#include <ws2tcpip.h> // For inet_pton
#include <stdio.h>
int main() {
struct in_addr ip_address;
char ip_string[] = "192.168.1.1";
// Convert the string representation to a network byte order 32-bit integer
// Use inet_pton for modern IPv4 address conversion
if (inet_pton(AF_INET, ip_string, &ip_address) == 1) {
printf("Successfully converted IP address: %s\n", ip_string);
// Accessing the S_addr member
printf("IP Address (u_long, network byte order): 0x%lX\n", ip_address.S_un.S_addr);
// You can also convert it back to a string (for demonstration)
char buffer[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, &ip_address, buffer, INET_ADDRSTRLEN) != NULL) {
printf("IP Address (string): %s\n", buffer);
}
} else {
printf("Error converting IP address: %s\n", ip_string);
}
return 0;
}
SOCKADDR_IN: A more general socket address structure that includes port information along with the IP address (using IN_ADDR).inet_addr: Converts an IPv4 dotted-decimal string to a 32-bit value. (Deprecated in favor of inet_pton).inet_ntoa: Converts an IN_ADDR structure to a dotted-decimal string. (Deprecated in favor of inet_ntop).inet_pton: Converts an IP address string in presentation format to its network representation.inet_ntop: Converts an IP address in its network representation to an IP address string in presentation format.inet_pton and inet_ntop for IP address string conversions, as they are more robust and support both IPv4 and IPv6.
S_addr member stores the IP address in network byte order. You may need to use functions like ntohl (network to host long) or htonl (host to network long) if you need to perform arithmetic operations on the address in host byte order.