home *** CD-ROM | disk | FTP | other *** search
- /*
- * $Author: reggers $
- * $Date: 1992/06/10 14:02:26 $
- * $Header: /usr/src/usr.local/utilities/sendopr/RCS/tcpopen.c,v 1.2 1992/06/10 14:02:26 reggers Exp $
- *
- * Abstract: open a connection to a host/service
- *
- * Original work by Reg Quinton; 30 Apr 1991
- */
-
- #include <stdio.h>
- #include <signal.h>
- #include <setjmp.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
-
- #ifndef SIGRET
- #define SIGRET int
- #endif
-
- #ifndef TIMEOUT
- #define TIMEOUT 60
- #endif
-
- static jmp_buf env; /* for jump back */
-
- static
- SIGRET catcher()
- { longjmp(env,1); }
-
- /* open a connection to some service on some host */
-
- int tcpopen(host,service)
- char *service, *host;
- { int unit;
- static struct sockaddr_in sin;
- static struct servent *sp;
- static struct hostent *hp;
- SIGRET (*oldsig)();
-
- oldsig=signal(SIGALRM,catcher);
-
- if (setjmp(env))
- { signal(SIGALRM,oldsig); alarm(0);
- return(-1);
- }
-
- alarm(TIMEOUT);
-
- /* this is straight line lifting from the 4.2BSD IPC Primer
- example of section 3.5... the famous figure 1 */
-
- if ((sp=getservbyname(service,"tcp")) == NULL)
- { fprintf(stderr,"Oops ... no such service \"%s\"\n",service);
- return(-1);
- }
-
- if ((hp=gethostbyname(host)) == NULL)
- { fprintf(stderr,"Oops ... unknown host \"%s\"\n",host);
- return(-1);
- }
-
- bzero((char *)&sin, sizeof(sin));
- bcopy(hp->h_addr,(char *)&sin.sin_addr,hp->h_length);
- sin.sin_family=hp->h_addrtype;
- sin.sin_port=sp->s_port;
-
- if ((unit=socket(AF_INET,SOCK_STREAM,0)) < 0)
- { fprintf(stderr,"Oops ... tcp/ip cannot open socket\n");
- return(-1);
- }
-
- if (connect(unit,(char *)&sin,sizeof(sin)) < 0)
- { fprintf(stderr,"Oops ... tcp/ip cannot connect to server\n");
- return(-1);
- }
-
- signal(SIGALRM,oldsig); alarm(0);
- return(unit);
- }
-