/* Agent Tcl
   Bob Gray
   24 June 1995

   tcpipBasic.cc

   This file implements the TCP/IP library routines.

   Copyright (c) 1995, Robert S. Gray Dartmouth College

   See the file "agent.terms" for information on usage and redistribution
   of this file and for a DISCLAIMER OF ALL WARRANTIES.
*/

#ifndef NO_PRAGMAS
#pragma implementation
#endif "tcpipTcl.h"

#include "platPorting.h"
#include "platSystem.h"
#include "mesgTcpip.h"
#include "mesgMachId.h"     // MachineId class

/* ------------------------------------------------------------------- */

#include "platTimers.h"
#include "platTimeval.h"
#include "genUtility.h"
#include "tcl.h"
#include "tcpipTcl.h"
#include "truefalse.h"

/* Tcpip_Getip

   Purpose: Get the IP number of a machine.

     Input: interp  = the current interpreter
	      	      (struct Tcl_Interp *)

	    seconds = maximum number of seconds to wait for the IP address
		      (double)

	    server  = name of the machine
		      (char *)

    Output: The procedure returns TCL_ERROR and sets the interpreter result 
	    to an appropriate error message on error.  Otherwise the 
	    procedure returns TCL_OK and fills in "ip".
*/

int Tcpip_Getip (Tcl_Interp *interp, double seconds, char *server, UINT_32 *ip)
{
    int returnCode;
    TcpipErrors tcpipRc;

	/* assertions on the parameters */

    assert (interp != NULL);
    assert (seconds >= 0.0);
    assert (server != NULL);
    assert (ip != NULL);

	/* set up the stop time and the MachineId instance */

    struct timeval stop = 
	TimevalUtil::addTimevals 
	    (SystemUtil::getCurrentWall(), TimevalUtil::secondsToTimeval(seconds));

    MachineId id = MachineId (DynamicString(server), UNKNOWN_IP);

	/* get the IP address */

    if (*server == '\0') {

	Tcl_AppendResult (interp, "the empty string is not a valid machine name", (char *) NULL);
	returnCode = TCL_ERROR;

    } else if ((tcpipRc = tcpip_getIP (id, stop)) == e_TCPIP_TIMEOUT) {

	Tcl_AppendResult (interp, "timeout while getting IP address of \"", id.getName().value(), "\"", (char *) NULL);
	returnCode = TCL_ERROR;

    } else if (tcpipRc != e_TCPIP_OK) {

        Tcl_AppendResult (interp, "unable to get IP address of \"", id.getName().value(), "\"", (char *) NULL);
	returnCode = TCL_ERROR;

    } else {

	*ip = id.getIp();
	returnCode = TCL_OK;
    }

    return (returnCode);
}
