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

int main(int argc, char **argv)
{
    // Declare and initialize variables
    WSADATA wsaData;
    char node_name[100] = "";
	struct hostent *hostptr;
	struct servent *servptr;
	// http://www.iana.org/assignments/port-numbers
	int services[12] = {23, 80, 25, 21, 53, 69, 110, 143, 70, 7, 13};
	int i;

	// Validate the parameters
    if (argc != 2)
	{
        printf("Usage: %s <host_name>\n", argv[0]);
		printf("Example: %s www.yahoo.com\n", argv[0]);
		// Just return with error
        return 1;
    }

	// Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
        printf("WSAStartup() failed with error code %ld\n", WSAGetLastError());
        return 1;
    }
	else
		printf("WSAStartup() looks fine!\n");

	strcpy_s(node_name, sizeof(node_name), argv[1]);
	// Here, name of server computer is expected, it is better
	// to add the server IP address functionality...
	hostptr = gethostbyname(node_name);
	
	if (hostptr == NULL)
	{
		printf("gethostbyname() failed with error code %ld\n", WSAGetLastError());
    }
	else
		printf("gethostbyname() is OK.\n Host name is %s\n", hostptr->h_name);

	for(i=0; i <= 10;i++)
	{
		// If this is null, getservbyport returns the first service
		// entry for which the port matches the s_port of the servent structure.
		servptr = getservbyport(ntohs(services[i]), NULL);
		
		if (servptr == NULL)
			printf ("\ngetservbyport() - %d failed with error code %ld\n", services[i], WSAGetLastError());
		else
		{
			// Print the related info
			printf("\ngetservbyport() is OK - %d\n", services[i]);
			printf(" Service name is %s\n", servptr->s_name);
			// Need to cast to host-byte order
			printf(" Port number is %u\n", ntohs(servptr->s_port));
			printf(" Protocol is %s\n", servptr->s_proto);
		}
	}
	WSACleanup();
    return 0;
}
