/*
 *		Samples\TcpIp\active.c
 *		Copyright (c) 2001, Z-World (jjb)
 *		This program demonstrates the tcp_open call.
 *
 * 	A simple demonstration of a TCP/IP session, by retrieving a
 * 	web page from a remote site.  Change DEST and PORT to the
 * 	remote machine.
 */

/*
 *  My identification:
 */
#define MY_IP_ADDRESS 	"10.10.6.100"
#define MY_NETMASK		"255.255.255.0"
#define MY_GATEWAY		"10.10.6.1"
#define MY_NAMESERVER	"10.10.6.1"

#use "dcrtcp.lib"

/*
 *  Remote computer to contact:
 */
#define  DEST 		"www.zworld.com"
#define  PORT 		80


int main()
{
	int bytes_read;
	char buffer[1024];
	longword  destIP;
	tcp_Socket socket;

	printf( "initializing..\n" );
	sock_init();

	if( 0L == (destIP = resolve(DEST)) ) {
		printf( "ERROR: Cannot resolve \"%s\" into an IP address\n", DEST );
		exit(2);
	}
	tcp_open(&socket,0,destIP,PORT,NULL);

	printf("Waiting for connection...\n");
	while(!sock_established(&socket) && sock_bytesready(&socket)==-1) {
		tcp_tick(NULL);
	}

	printf("Connection established, sending get request...\n");

	/*
	 *  If don't send the HTTP version number, then server believes we are
	 *  a pre-1.0 version client.
	 */
	sock_write(&socket,"GET /\r\n\r\n",9);

	/*
	 *  When tcp_tick()-ing on a specific socket, we get non-zero return while
	 *  it is active, and zero when it is closed (as used here).
	 */
	do {
		bytes_read=sock_fastread(&socket,buffer,sizeof(buffer)-1);

		if(bytes_read>0) {
			buffer[bytes_read]=0;
			/*
			 * By using the "%s" format, if there are "%" in the buffer, printf()
			 *  won't try to interpret them!
			 */
			printf("%s",buffer);
		}
	} while(tcp_tick(&socket));

	printf("\nConnection closed...\n");
	return 0;
}
