/*
* on Unix:
* cc -c connector.c
* cc -o connector connector.o
*
* on Windows NT:
* open connector.c in Visual Studio
* press 'F7' to link -- a project to be created
* add wsock32.lib to the link section under project setting
* press 'F7' again
*
* running:
* type 'connector' for usage
*/
/*
s - SOCKET
sec - timeout seconds
usec - timeout microseconds
x - select status
*/
SOCKET xnet_select(SOCKET s, int sec, int usec, short x)
{
int st = errno;
struct timeval to;
fd_set fs;
to.tv_sec = sec;
to.tv_usec = usec;
FD_ZERO(&fs);
FD_SET(s, &fs);
switch(x){
case READ_STATUS:
st = select(s+1, &fs, 0, 0, &to);
break;
case WRITE_STATUS:
st = select(s+1, 0, &fs, 0, &to);
break;
case EXCPT_STATUS:
st = select(s+1, 0, 0, &fs, &to);
break;
}
return(st);
}
int tcp_connect(const char *host, const unsigned short port)
{
unsigned long non_blocking = 1;
unsigned long blocking = 0;
int ret = 0;
char * transport = "tcp";
struct hostent *phe; /* pointer to host information entry */
struct protoent *ppe; /* pointer to protocol information entry*/
struct sockaddr_in sin; /* an Internet endpoint address */
SOCKET s; /* socket descriptor and socket type */
int error;
#ifdef WIN32
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 0 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we couldn't find a usable */
/* WinSock DLL. */
printf("can't initialize socket library\n");
exit(0);
}
}
#endif
if ((sin.sin_port = htons(port)) == 0)
err_quit("invalid port \"%d\"\n", port);
/* Map host name to IP address, allowing for dotted decimal */
if ( phe = gethostbyname(host) )
memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
else if ( (sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE )
err_quit("can't get \"%s\" host entry\n", host);
/* Map transport protocol name to protocol number */
if ( (ppe = getprotobyname(transport)) == 0)
err_quit("can't get \"%s\" protocol entry\n", transport);
/* Allocate a socket */
s = socket(PF_INET, SOCK_STREAM, ppe->p_proto);
if (s < 0)
err_quit("can't create socket: %s\n", strerror(errno));