/*****************************************************

	dns_look.c
	Copyright (C) Z-World, 2001

	Demonstrate use of DeviceMate to perform DNS lookups.

	The \samples\dmunit\tcp.c program must be running on the
	DeviceMate processor.  The DeviceMate must be correctly
	configured to be able to access a domain name server.
	
******************************************************/

/* Request use of TCP services */
#define USE_TC_TCPIP

/*
 * Uncomment this line if this program will be loaded over ethernet. This will
 * force the DevMate communication to use serial port A, re-using the programming
 * link that was used to download the program.
 */
//#define USE_TC_LOADER

#ifdef CC_VER
	/* Dynamic C */
	#memmap xmem
	#use "tc_conf.lib"
#else
	/* Non-Rabbit */
	#include "tc_conf.h"
	#include <stdio.h>	
#endif

int main()
{
	int rc, rc1, rc2;
	uint16 request_id, request_id2;
	uint32 ip, ip2;
	char hostnames[129];
	char * hostname1, * hostname2, * h;

	printf("Initializing 1...\n");
	devmate_init();

	/* Initialize TCP. */
	printf("2...\n");
	rc = devmate_sock_init(NULL, NULL, NULL, NULL, NULL, NULL);
	if (rc <= 0) {
		printf("Failed devmate_sock_init.\n");
		exit(20);
	}


	/*
	 * Do DNS lookups
	 */
	for (;;) {
		printf("Enter hostname(s) to lookup:\n");
#ifdef __DC__
		gets(hostnames);
#else
		fgets(hostnames, sizeof(hostnames), stdin);
#endif
		hostname1 = NULL;
		hostname2 = NULL;
		for (h = hostnames; isspace(*h); h++);
		if (*h) {
			hostname1 = h++;
			while (*h && !isspace(*h)) h++; 
			if (*h) {
				*h++ = 0;
				while (isspace(*h)) h++;
				if (*h) {
					hostname2 = h;
					while (*h && !isspace(*h)) h++;
					*h = 0;
				}
			}
		}
		else
			continue;
		request_id = 0;
		request_id2 = 0;
		rc1 = 0;
		rc2 = 0;
		do {
			if (!rc1)
				rc1 = devmate_ip_resolve(&request_id, hostname1, &ip);
			if (hostname2 && !rc2)
				rc2 = devmate_ip_resolve(&request_id2, hostname2, &ip2);
			devmate_tick();
		} while (!rc1 || (hostname2 && !rc2));
		if (rc1 < 0)
			printf("Lookup '%s' failed %d\n", hostname1, rc1);
		else
			printf("IP address of '%s' = %08lx\n", hostname1, ip);
		if (rc2 < 0)
			printf("Lookup '%s' failed %d\n", hostname2, rc2);
		else if (rc2)
			printf("IP address of '%s' = %08lx\n", hostname2, ip2);
	}
}
