IN_ADDR Structure

#include <winsock2.h>

Syntax


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;
};
            

Members

The in_addr structure stores an IPv4 address.

The structure contains a union with the following members:

S_un

A union that can hold the IPv4 address in different formats.

Remarks

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).

Example Usage

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;
}
        

Related Structures and Functions

Note: For modern network programming, it is recommended to use inet_pton and inet_ntop for IP address string conversions, as they are more robust and support both IPv4 and IPv6.
Important: Always remember that the 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.