#include <winsock2.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    // Declare and initialize variables
    WSADATA wsaData;
    int iResult;
    unsigned long ulAddr = INADDR_NONE;
	ULONG TempBuff = 0;
	struct sockaddr_in saSample;

    // Validate the parameters
    if (argc != 2)
	{
        printf("Usage: %s <IPv4 address>\n", argv[0]);
        printf("  inet_addr() converts a string containing an\n");
        printf("  IPv4 address in one of the supported formats\n");
        printf("  to a unsigned long representing an IN_ADDR\n");
		printf("Example: %s 209.131.36.158\n", argv[0]);
        return 1;
    }
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0)
	{
        printf("WSAStartup() failed with error code %ld\n", WSAGetLastError());
        return 1;
    }
	
	// Just for demonstration, call inet_addr(). If the call
	// succeeds, the result variable will hold a IN_ADDR structure
    ulAddr = inet_addr(argv[1]);

    if ( ulAddr == INADDR_NONE )
	{
        printf("inet_addr() failed and returned INADDR_NONE\n");
        WSACleanup();
        return 1;
    }   
    
    if (ulAddr == INADDR_ANY) {
        printf("inet_addr() failed and returned INADDR_ANY\n");
        WSACleanup();
        return 1;  
    }

    printf("inet_addr() returned success!\n");
	// Retrieve address and print out the hex/dec/octal bytes
	printf("  Hex:\t\t0X%0X\n", ulAddr);
	printf("  Decimal:\t%ul\n", ulAddr);
	printf("  Octal:\t0%o\n", ulAddr);
	
	// Then, ready to be used		
	saSample.sin_family = AF_INET;
	// In typical app. we can be directly use:
	//		usesaSample.sin_addr.s_addr = inet_addr(argv[1]);
	saSample.sin_addr.s_addr = ulAddr;
	saSample.sin_port = htons(1234);
	
	// More codes, create socket, bind, connect etc.

	// Revert the process using inet_ntoa() just for the address part
	if(inet_ntoa(saSample.sin_addr) != NULL)
	{
		printf("inet_ntoa() return success!\n");
		printf("The IP address is %s\n", inet_ntoa(saSample.sin_addr));
	}
	else
		printf("inet_ntoa() failed with error code %ld\n", WSAGetLastError());

    WSACleanup();
    return 0;
}
