home *** CD-ROM | disk | FTP | other *** search
- /*
-
- portname.c, part of
- faucet and hose: network pipe utilities
- Copyright (C) 1992 Robert Forsman
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
- */
-
- #include <stdio.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include <netdb.h>
- #include <netinet/in.h>
-
- int name_to_inet_port(portname)
- char *portname;
- /* This procedure converts a character string to a port number. It looks
- up the service by name and if there is none, then it converts the string
- to a number with sscanf */
- {
- struct servent *p;
-
- if (portname==NULL)
- return 0;
-
- p = getservbyname(portname,"tcp");
- if (p!=NULL)
- {
- return p->s_port;
- }
- else
- {
- int port;
- if (sscanf(portname,"%i",&port)!=1)
- {
- return 0;
- }
- else
- return htons(port);
- }
- }
-
- int
- convert_hostname(name, addr)
- char *name;
- struct in_addr *addr;
- {
- struct hostent *hp;
- int len;
-
- hp = gethostbyname(name);
- if (hp != NULL)
- bcopy(hp->h_addr,addr,hp->h_length);
- else
- {
- int count;
- unsigned int a1,a2,a3,a4;
- count = sscanf(name,"%i.%i.%i.%i%n", &a1, &a2, &a3, &a4, &len);
- if (4!=count || 0!=name[len] )
- return 0;
- addr->S_un.S_un_b.s_b1 = a1;
- addr->S_un.S_un_b.s_b2 = a2;
- addr->S_un.S_un_b.s_b3 = a3;
- addr->S_un.S_un_b.s_b4 = a4;
- }
- return 1;
- }
-
-
- int
- bindlocal(fd, name, domain)
- int fd, domain;
- char *name;
- {
- struct sockaddr laddr;
- int countdown;
- int rval;
-
- if (domain==AF_INET)
- {
- struct sockaddr_in *srv = (struct sockaddr_in*)&laddr;
-
- srv->sin_family = AF_INET;
- srv->sin_addr.s_addr = INADDR_ANY;
-
- srv->sin_port = name_to_inet_port(name);
-
- if (srv->sin_port==0)
- {
- fprintf(stderr, "port %s unknown\n", name);
- return 0;
- }
- }
- else
- {
- struct sockaddr_un *srv = (struct sockaddr_un *)&laddr;
-
- srv->sun_family = AF_UNIX;
- strcpy(srv->sun_path, name);
- }
-
- countdown= (domain==AF_UNIX)?1:10;
- do {
- rval = bind(fd, &laddr, sizeof(laddr));
- if (rval)
- if (errno==EADDRINUSE && --countdown>0)
- {
- fprintf(stderr,"Address %s in use, sleeping 10.\n",
- name);
- sleep (10);
- fprintf(stderr,"Trying again . . .\n");
- }
- else
- return 0;
- } while (rval);
-
- return 1;
- }
-