inet_pton Function

Header: ws2tcpip.h

Library: Ws2_32.lib

DLL: Ws2_32.dll

Syntax

INT inet_pton( _In_ INT AddressFamily, _In_ PCSTR pszString, _Out_ PVOID pAddr );

Parameters

Return Value

If the function succeeds, the return value is 1. The pszString parameter points to a valid IP address.

If the function fails, the return value is 0. The pszString parameter does not point to a valid IP address.

If an unknown flag is passed in the AddressFamily parameter, the return value is -1.

Remarks

The inet_pton function converts an IPv4 or IPv6 network address from its presentation (character) format to its numeric binary form.

This function is a more modern and preferred alternative to functions like inet_addr and inet_ntoa.

The pszString parameter can contain an IPv4 address in dotted-decimal notation (e.g., "192.168.1.1") or an IPv6 address (e.g., "::1", "2001:db8::1").

The pAddr parameter must point to a structure of the appropriate size for the specified AddressFamily:

Example

Converting an IPv4 Address

#include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> // Link with Ws2_32.lib #pragma comment(lib, "Ws2_32.lib") int main() { WSADATA wsaData; INT iResult; char ipstr[INET_ADDRSTRLEN]; struct sockaddr_in sa; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } const char *IP4toConvert = "192.168.1.1"; iResult = inet_pton(AF_INET, IP4toConvert, &(sa.sin_addr)); if (iResult > 0) { printf("inet_pton successful\n"); // Convert the IP address back to a string for display inet_ntop(AF_INET, &(sa.sin_addr), ipstr, sizeof ipstr); printf("Converted IP: %s\n", ipstr); } else if (iResult == 0) { printf("inet_pton failed: invalid address string\n"); } else { printf("inet_pton failed with error: %d\n", WSAGetLastError()); } WSACleanup(); return 0; }

Converting an IPv6 Address

#include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> // Link with Ws2_32.lib #pragma comment(lib, "Ws2_32.lib") int main() { WSADATA wsaData; INT iResult; char ipstr[INET6_ADDRSTRLEN]; struct sockaddr_in6 sa6; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } const char *IP6toConvert = "2001:db8::1"; iResult = inet_pton(AF_INET6, IP6toConvert, &(sa6.sin6_addr)); if (iResult > 0) { printf("inet_pton successful\n"); // Convert the IP address back to a string for display inet_ntop(AF_INET6, &(sa6.sin6_addr), ipstr, sizeof ipstr); printf("Converted IP: %s\n", ipstr); } else if (iResult == 0) { printf("inet_pton failed: invalid address string\n"); } else { printf("inet_pton failed with error: %d\n", WSAGetLastError()); } WSACleanup(); return 0; }

Requirements

Minimum supported client: Windows Vista [desktop apps | UWP apps]

Minimum supported server: Windows Server 2008 [desktop apps | UWP apps]

Header: ws2tcpip.h

Library: Ws2_32.lib

DLL: Ws2_32.dll