Пример #1
0
struct servent * getservbyport(int port,
		const char *proto) {
	struct servent *se;

	if (proto == NULL) {
		return NULL;
	}

	setservent(1);
	port = htons((unsigned short)port);

	while ((se = getservent()) != NULL) {
		/* same protocol? */
		if (strcmp(proto, se->s_proto) != 0) {
			continue; /* not same. try again */
		}
		/* same port? */
		if (se->s_port == port) {
			break;
		}
		/* nope. try again */
	}

	endservent();

	return se;
}
Пример #2
0
void
nw_setservent(int stayopen)
{
#ifdef HAS_SETSERVENT
        setservent(stayopen);
#endif
}
Пример #3
0
Файл: inet.c Проект: AnthraX1/rk
static int
read_services(void)
{
  struct servent *se;
  struct service *item;

  setservent(1);
  while((se=getservent())) {
	/* Allocate a service entry. */
	item = (struct service *) malloc(sizeof(struct service));
	if (item == NULL) perror("netstat"); 
	item->name = strdup(se->s_name);
	item->number = se->s_port;

	/* Fill it in. */
	if (! strcmp(se->s_proto, "tcp")) {
		add2list(&tcp_name,item);
	} else if (! strcmp(se->s_proto, "udp")) {
		add2list(&udp_name,item);
	} else if (! strcmp(se->s_proto, "raw")) {
		add2list(&raw_name,item);
	}
  }
  endservent();
  return(0);
}
struct servent *
getservbyport(
	int port,
	const char *proto)
{
	register struct servent *p;

#ifdef YP
	extern int ___getservbyport_yp;
	extern char *___getservbyproto_yp;

	___getservbyport_yp = port;
	___getservbyproto_yp = (char *)proto;
#endif

	setservent(_serv_stayopen);
	while ( (p = getservent()) ) {
		if (p->s_port != port)
			continue;
		if (proto == 0 || strcmp(p->s_proto, proto) == 0)
			break;
	}
	if (!_serv_stayopen)
		endservent();

#ifdef YP
	___getservbyport_yp = 0;
	___getservbyproto_yp = NULL;
#endif

	return (p);
}
Пример #5
0
static int
services(int argc, char *argv[])
{
	struct servent	*se;
	int		i, rv = RV_OK;

	setservent(1);
	if (argc == 2) {
		while ((se = getservent()) != NULL)
			SERVICESPRINT;
	} else {
		for (i = 2; i < argc; i++) {
			const char	*err;
			long long	id;
			char *proto = strchr(argv[i], '/');

			if (proto != NULL)
				*proto++ = '\0';
			id = strtonum(argv[i], 0, UINT_MAX, &err);
			if (!err)
				se = getservbyport(htons((u_short)id), proto);
			else
				se = getservbyname(argv[i], proto);
			if (se != NULL)
				SERVICESPRINT;
			else {
				rv = RV_NOTFOUND;
				break;
			}
		}
	}
	endservent();
	return rv;
}
Пример #6
0
/* libc_hidden_proto(getservbyname_r) */
int getservbyname_r(const char *name, const char *proto,
	struct servent * result_buf, char * buf, size_t buflen,
	struct servent ** result)
{
    register char **cp;
    int ret;

    __UCLIBC_MUTEX_LOCK(mylock);
    setservent(serv_stayopen);
    while (!(ret=getservent_r(result_buf, buf, buflen, result))) {
	if (strcmp(name, result_buf->s_name) == 0)
	    goto gotname;
	for (cp = result_buf->s_aliases; *cp; cp++)
	    if (strcmp(name, *cp) == 0)
		goto gotname;
	continue;
gotname:
	if (proto == 0 || strcmp(result_buf->s_proto, proto) == 0)
	    break;
    }
    if (!serv_stayopen)
	endservent();
    __UCLIBC_MUTEX_UNLOCK(mylock);
    return *result?0:ret;
}
Пример #7
0
static void *
services_mp_init_func(void)
{
	TRACE_IN(services_mp_init_func);
	setservent(0);
	TRACE_OUT(services_mp_init_func);

	return (NULL);
}
Пример #8
0
/*
 * Like strtol, but also translates service names into port numbers
 * for some protocols.
 * In particular:
 *	proto == -1 disables the protocol check;
 *	proto == IPPROTO_ETHERTYPE looks up an internal table
 *	proto == <some value in /etc/protocols> matches the values there.
 * Returns *end == s in case the parameter is not found.
 */
static int
strtoport(char *s, char **end, int base, int proto)
{
	char *p, *buf;
	char *s1;
	int i;

	*end = s; 		/* default - not found */
	if ( *s == '\0')
		return 0; 	/* not found */

	if (isdigit(*s))
		return strtol(s, end, base);

	/*
	 * find separator. '\\' escapes the next char.
	 */
	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) {
		if (*s1 == '\\' && s1[1] != '\0')
			s1++;
	}

	buf = malloc(s1 - s + 1);
	if (buf == NULL)
		return 0;

	/*
	 * copy into a buffer skipping backslashes
	 */
	for (p = s, i = 0; p != s1 ; p++)
		if ( *p != '\\')
			buf[i++] = *p;
	buf[i++] = '\0';

	if (proto == IPPROTO_ETHERTYPE) {
		i = match_token(ether_types, buf);
		free(buf);
		if (i != -1) {	/* found */
			*end = s1;
			return i;
		}
	} else {
		struct protoent *pe = NULL;
		struct servent *se;

		if (proto != 0)
			pe = getprotobynumber(proto);
		setservent(1);
		se = getservbyname(buf, pe ? pe->p_name : NULL);
		free(buf);
		if (se != NULL) {
			*end = s1;
			return ntohs(se->s_port);
		}
	}
	return 0; 	/* not found */
}
Пример #9
0
/* servid */
static int _servid(char const * protocol, char const * service)
{
	struct servent * se;

	setservent(1);
	if((se = getservbyname(service, protocol)) == NULL)
		return _servid_error(service, 1);
	printf("%d/%s\n", ntohs(se->s_port), se->s_proto);
	return 0;
}
Пример #10
0
setservent_r(int stay_open)
#endif
{
#ifdef SERV_R_ENT_UNUSED
	SERV_R_ENT_UNUSED;
#endif
	setservent(stay_open);
#ifdef SERV_R_SET_RESULT
	return (SERV_R_SET_RESULT);
#endif
}
Пример #11
0
/*
 * setup parse
 */
void
zonec_setup_parser(namedb_type* db)
{
	region_type* rr_region = region_create(xalloc, free);
	parser = zparser_create(db->region, rr_region, db);
	assert(parser);
	/* Unique pointers used to mark errors.	 */
	error_dname = (dname_type *) region_alloc(db->region, 1);
	error_domain = (domain_type *) region_alloc(db->region, 1);
	/* Open the network database */
	setprotoent(1);
	setservent(1);
}
int main (void)
{
	struct servent   service;
	struct servent * retour;
	char   buffer [256];
	
	setservent(0);
	while(getservent_r(& service, buffer, 256, & retour) == 0)
		fprintf(stdout, "%s ", service.s_name);
	endservent();
	fprintf(stdout, "\n");
	return EXIT_SUCCESS;
}
Пример #13
0
/* The getservent() function reads the next line from the file `/etc/services'
   and returns a structure servent containing the broken out fields from the
   line.  The `/etc/services' file is opened if necessary. */
struct servent *
getservent (void)
{
  char line[MAX_NAMLEN], *end, *p;
  int done = 0, i, n, a;
  struct servent *e = NULL;

  /* Ensure a open file.  */
  if (scm_i_servent.fd == NULL || feof (scm_i_servent.fd))
    {
      setservent (1);
      if (scm_i_servent.fd == NULL)
	return NULL;
    }

  while (!done)
    {
      /* Get new line.  */
      if (fgets (line, MAX_NAMLEN, scm_i_servent.fd) != NULL)
	{
	  end = scm_i_socket_uncomment (line);

	  /* Scan the line.  */
	  if ((i = sscanf (line, "%s %d/%s%n", 
			   scm_i_servent.name,
			   &scm_i_servent.port, 
			   scm_i_servent.proto, &n)) != 3)
	    continue;

	  /* Scan the remaining aliases.  */
	  p = line + n;
	  for (a = 0; a < MAX_ALIASES && p < end && i != -1 && n > 1; 
	       a++, p += n)
	    i = sscanf (p, "%s%n", scm_i_servent.alias[a], &n);

	  /* Prepare the return value.  */
	  e = &scm_i_servent.ent;
	  e->s_name = scm_i_servent.name;
	  e->s_port = htons (scm_i_servent.port);
	  e->s_proto = scm_i_servent.proto;
	  e->s_aliases = scm_i_servent.aliases;
	  scm_i_servent.aliases[a] = NULL;
	  while (a--)
	    scm_i_servent.aliases[a] = scm_i_servent.alias[a];
	  done = 1;
	}
      else
	break;
    }
  return done ? e : NULL;
}
Пример #14
0
struct servent *
getservbyport(int port, const char *proto)
{
    register struct servent *p;

    setservent(_serv_stayopen);
    while (p = getservent()) {
        if (p->s_port != port)
            continue;
        if (proto == 0 || strcmp(p->s_proto, proto) == 0)
            break;
    }
    if (!_serv_stayopen)
        endservent();
    return (p);
}
Пример #15
0
static int
servent_fill_test_data(struct servent_test_data *td)
{
	struct servent *serv;
		
	setservent(1);
	while ((serv = getservent()) != NULL) {
		if (servent_test_correctness(serv, NULL) == 0)
			TEST_DATA_APPEND(servent, td, serv);
		else
			return (-1);
	}
	endservent();
	
	return (0);
}
Пример #16
0
int main (void) {
 struct servent *pht;
 char *pct;
 int i;

 setservent (1);

 while ((pht = getservent ()) != NULL) {
   printf ("Официальное имя сервиса: %s\n", pht->s_name);
   printf ("Альтернативные имена:\n");
   for (i = 0; (pct = pht->s_aliases [i]) != NULL; i++) {
     printf ("  %s\n", pct);
   }
   printf ("Номер порта: %d\n", ntohs ((in_port_t) pht->s_port));
   printf ("Имя протокола: %s\n\n", pht->s_proto);
 }

 if ((pht = getservbyport (htons ((in_port_t) 21), "udp")) != NULL) {
   printf ("Официальное имя сервиса: %s\n", pht->s_name);
   printf ("Альтернативные имена:\n");
   for (i = 0; (pct = pht->s_aliases [i]) != NULL; i++) {
     printf ("  %s\n", pct);
   }
   printf ("Номер порта: %d\n", ntohs ((in_port_t) pht->s_port));
   printf ("Имя протокола: %s\n\n", pht->s_proto);
 } else {
   perror ("GETSERVBYPORT");
 }

 if ((pht = getservbyport (htons ((in_port_t) 21), (char *) NULL)) != NULL) {
   printf ("Официальное имя сервиса: %s\n", pht->s_name);
   printf ("Альтернативные имена:\n");
   for (i = 0; (pct = pht->s_aliases [i]) != NULL; i++) {
     printf ("  %s\n", pct);
   }
   printf ("Номер порта: %d\n", ntohs ((in_port_t) pht->s_port));
   printf ("Имя протокола: %s\n\n", pht->s_proto);
 } else {
   perror ("GETSERVBYPORT");
 }

 endservent ();

 return 0;
}
Пример #17
0
void findservice(int port) {
  struct servent *sep;
  char **cpp;
  int hbo,found=0;
  setservent(1);
  while((sep=getservent())!=NULL) {
    hbo=ntohs(sep->s_port);
    if (hbo==port) {
      printf("%d/%s\t%s",hbo,sep->s_proto,sep->s_name);
      for(cpp=sep->s_aliases;*cpp;++cpp)
	printf(" %s",*cpp);
      putchar('\n');
      found=1;
    }
  }
  endservent();
  if (!found)
    fprintf(stderr,"%s: port %d has no name on this system.\n",progname,port);
} /* void findservice(int port) */
Пример #18
0
/* libc_hidden_proto(getservbyport_r) */
int getservbyport_r(int port, const char *proto,
	struct servent * result_buf, char * buf,
	size_t buflen, struct servent ** result)
{
    int ret;

    __UCLIBC_MUTEX_LOCK(mylock);
    setservent(serv_stayopen);
    while (!(ret=getservent_r(result_buf, buf, buflen, result))) {
	if (result_buf->s_port != port)
	    continue;
	if (proto == 0 || strcmp(result_buf->s_proto, proto) == 0)
	    break;
    }
    if (!serv_stayopen)
	endservent();
    __UCLIBC_MUTEX_UNLOCK(mylock);
    return *result?0:ret;
}
Пример #19
0
static void
test_services (void)
{
  struct servent *sptr;

  sptr = getservbyname ("domain", "tcp");
  output_servent ("getservbyname (\"domain\", \"tcp\")", sptr);

  sptr = getservbyname ("domain", "udp");
  output_servent ("getservbyname (\"domain\", \"udp\")", sptr);

  sptr = getservbyname ("domain", NULL);
  output_servent ("getservbyname (\"domain\", NULL)", sptr);

  sptr = getservbyname ("not-existant", NULL);
  output_servent ("getservbyname (\"not-existant\", NULL)", sptr);

  /* This shouldn't return anything.  */
  sptr = getservbyname ("", "");
  output_servent ("getservbyname (\"\", \"\")", sptr);

  sptr = getservbyname ("", "tcp");
  output_servent ("getservbyname (\"\", \"tcp\")", sptr);

  sptr = getservbyport (htons(53), "tcp");
  output_servent ("getservbyport (htons(53), \"tcp\")", sptr);

  sptr = getservbyport (htons(53), NULL);
  output_servent ("getservbyport (htons(53), NULL)", sptr);

  sptr = getservbyport (htons(1), "udp"); /* shouldn't exist */
  output_servent ("getservbyport (htons(1), \"udp\")", sptr);

  setservent (0);
  do
    {
      sptr = getservent ();
      output_servent ("getservent ()", sptr);
    }
  while (sptr != NULL);
  endservent ();
}
Пример #20
0
/*
  parse a IP:port pair
*/
int ctdb_parse_address(struct ctdb_context *ctdb,
		       TALLOC_CTX *mem_ctx, const char *str,
		       struct ctdb_address *address)
{
	struct servent *se;

	setservent(0);
	se = getservbyname("ctdb", "tcp");
	endservent();
	
	address->address = talloc_strdup(mem_ctx, str);
	CTDB_NO_MEMORY(ctdb, address->address);

	if (se == NULL) {
		address->port = CTDB_PORT;
	} else {
		address->port = ntohs(se->s_port);
	}
	return 0;
}
Пример #21
0
/* Services are represented by the port number portion of the address. Each
 * service is offered on a unique, well-known port number. We can map a
 * service name to a port number with getservbyname(), map a port number to
 * a service name with getservbyport(), or scan the services database
 * sequentially with getservent().
 *
 * #include <netdb.h>
 * void endservent(void);
 * struct servent *getservbyname(const char *name, const char *proto);
 * struct servent *getservbyport(int port, const char *proto);
 * struct servent *getservent(void):
 * void setservent(int stayopen);
 *
 * These functions shall retrieve information about network services.
 *
 * The setservent() function shall open a connection to the database, and
 * set the next entry to the first entry. If the stayopen argument is non-
 * zero, the net database shall not be closed after each call to the
 * getservent() function (either directly, or indirectly through one of the
 * other getserv*() functions).
 *
 * The getservent() function shall read the next entry of the database,
 * opending and closing a connection to the database as necessary.
 *
 * The getservbyname() function shall search the database from the beginning
 * and find the first entry for which the service name specified by name
 * matches the s_name member and the protocol name specified by proto
 * matches the s_proto mumber, opening and closing a connection to the
 * database necessary. If proto is a null pointer, any value of the s_proto
 * member shall be matched. 当 proto 是NULL指针时,将匹配任意的协议名,但是
 * getservbyname()函数还是只返回第一项匹配的指针,不会返回多项.这里的"匹配
 * 任意协议名"应该是指不判断协议名.
 *
 * The getservbyport() function shall search the database from the beginning
 * and find the first entry for which the port specified by port matches the
 * s_port member and the protocol name specified by proto matches the
 * s_proto member, opening and closing a connection to the database as
 * necessary. If proto is a null pointer, any value of the s_proto member
 * shall be matched. The port argument shall be a value obtained by
 * converting a uint16_t in network byte order to int. 即 port 参数的值
 * 是网络字节序的,经过测试,要调用htons()函数来转换得到网络字节序的值,不能
 * 使用htonl()函数, htonl(80) 得到的值是0x50000000, htons(80) 得到的值是
 * 0x5000, 两者的结果是不同的.
 *
 * The endservent() function shall close the database, releasing any open
 * file descriptor.
 *
 * These functions need not be thread-safe.
 *
 * Upon successful completion, getservbyname(), getservbyport(), and
 * getservent() return a pointer to a servent structure if the requested
 * entry was found, and a null pointer if the end of the database was
 * reached or the requested entry was not found. Otherwise, a null pointer
 * is returned. No errors are defined.
 *
 * Linux 中, struct servent 结构体定义如下:
 * struct servent {
 *      char    *s_name;    // official service name
 *      char   **s_aliases; // alias list, terminated by NULL
 *      int      s_port;    // The port number for the service given
 *                          // in network byte order
 *      char     *s_proto;  // protocol to use with this service
 * };
 *
 * 查看执行结果,发现输出的服务名和 /etc/services 文件里面的服务名是一样的.
 */
int main(void)
{
    struct servent *serv;
    int i, port;

    while ((serv = getservent()) != NULL)
        printservent(serv);
    endservent();

    printf("========= getservbyname: name --> echo, proto --> tcp\n");
    if ((serv = getservbyname("echo", "tcp")) != NULL)
        printservent(serv);

    /* 虽然 echo 服务可以使用tcp协议,也可以使用udp协议,但是下面的语句还是
     * 只会返回其中一项的值,指定getservbyname()函数的第二个参数为NULL,并
     * 不会两个echo服务 (使用tcp协议的echo和使用udp协议的echo).
     */
    printf("========= getservbyname: name --> echo, proto --> NULL\n");
    if ((serv = getservbyname("echo", NULL)) != NULL)
        printservent(serv);

    printf("========= getservbyprot: port --> 80, proto --> tcp\n");
    port = htons(80);
    printf("port: host 80 --> network is: %#x\n", port);
    if ((serv = getservbyport(port, "tcp")) != NULL)
        printservent(serv);

    printf("========= setservent() =========\n");
    if ((serv = getservent()) != NULL)
        printservent(serv);
    setservent(0);

    printf("========= after setservent() =========\n");
    for (i = 0; i < 2; ++i)
        if ((serv = getservent()) != NULL)
            printservent(serv);
    endservent();

    return 0;
}
Пример #22
0
/*
 * services
 */
static int
services(int argc, char *argv[])
{
	struct servent	*se;
	unsigned long	id;
	char		*proto;
	int		i, rv;

	assert(argc > 1);
	assert(argv != NULL);

#define SERVICESPRINT	printfmtstrings(se->s_aliases, "  ", " ", \
			    "%-16s  %5d/%s", \
			    se->s_name, ntohs(se->s_port), se->s_proto)

	setservent(1);
	rv = RV_OK;
	if (argc == 2) {
		while ((se = getservent()) != NULL)
			SERVICESPRINT;
	} else {
		for (i = 2; i < argc; i++) {
			proto = strchr(argv[i], '/');
			if (proto != NULL)
				*proto++ = '\0';
			if (parsenum(argv[i], &id))
				se = getservbyport(htons((u_short)id), proto);
			else
				se = getservbyname(argv[i], proto);
			if (se != NULL)
				SERVICESPRINT;
			else {
				rv = RV_NOTFOUND;
				break;
			}
		}
	}
	endservent();
	return rv;
}
Пример #23
0
static int read_services(void)
{
    struct servent *se;
    struct protoent *pe;
    struct service *item;

    setservent(1);
    while ((se = getservent())) {
	/* Allocate a service entry. */
	item = (struct service *) xmalloc(sizeof(struct service));
	item->name = strdup(se->s_name);
	item->number = se->s_port;

	/* Fill it in. */
	if (!strcmp(se->s_proto, "tcp")) {
	    add2list(&tcp_name, item);
	} else if (!strcmp(se->s_proto, "udp")) {
	    add2list(&udp_name, item);
	} else if (!strcmp(se->s_proto, "sctp")) {
	    add2list(&sctp_name, item);
	} else if (!strcmp(se->s_proto, "raw")) {
	    add2list(&raw_name, item);
	} else { /* ddp, dccp */
	    free(item->name);
	    free(item);
	}
    }
    endservent();
    setprotoent(1);
    while ((pe = getprotoent())) {
	/* Allocate a service entry. */
	item = (struct service *) xmalloc(sizeof(struct service));
	item->name = strdup(pe->p_name);
	item->number = htons(pe->p_proto);
	add2list(&raw_name, item);
    }
    endprotoent();
    return (0);
}
Пример #24
0
struct servent *
getservbyname(const char *name, const char *proto)
{
	register struct servent *p;
	register char **cp;

	setservent(_serv_stayopen);
	while (p = getservent()) {
		if (strcmp(name, p->s_name) == 0)
			goto gotname;
		for (cp = p->s_aliases; *cp; cp++)
			if (strcmp(name, *cp) == 0)
				goto gotname;
		continue;
gotname:
		if (proto == 0 || strcmp(p->s_proto, proto) == 0)
			break;
	}
	if (!_serv_stayopen)
		endservent();
	return (p);
}
Пример #25
0
struct servent *
getservbyname(
	const char *name, 
	const char *proto )
{
	register struct servent *p;
	register char **cp;

#ifdef YP
	extern char *___getservbyname_yp;
	extern char *___getservbyproto_yp;

	___getservbyname_yp = (char *)name;
	___getservbyproto_yp = (char *)proto;
#endif

	setservent(_serv_stayopen);
	while ( (p = getservent()) ) {
		if (strcmp(name, p->s_name) == 0)
			goto gotname;
		for (cp = p->s_aliases; *cp; cp++)
			if (strcmp(name, *cp) == 0)
				goto gotname;
		continue;
gotname:
		if (proto == 0 || strcmp(p->s_proto, proto) == 0)
			break;
	}
	if (!_serv_stayopen)
		endservent();

#ifdef YP
	___getservbyname_yp = NULL;
	___getservbyproto_yp = NULL;
#endif

	return (p);
}
Пример #26
0
int getservent_r(struct servent *result_buf,
				 char *buf, size_t buflen, struct servent **result)
{
	char **tok = NULL;
	const size_t aliaslen = sizeof(char *) * MAXTOKENS;
	int ret = ERANGE;

	*result = NULL;
	if (buflen < aliaslen
		|| (buflen - aliaslen) < BUFSZ + 1)
		goto DONE_NOUNLOCK;

	__UCLIBC_MUTEX_LOCK(mylock);
	ret = ENOENT;
	if (servp == NULL)
		setservent(serv_stayopen);
	if (servp == NULL)
		goto DONE;

	servp->data = buf;
	servp->data_len = aliaslen;
	servp->line_len = buflen - aliaslen;
	/* <name>[[:space:]]<port>/<proto>[[:space:]][<aliases>] */
	if (!config_read(servp, &tok, MAXTOKENS - 1, MINTOKENS, "# \t/", PARSE_NORMAL)) {
		goto DONE;
	}
	result_buf->s_name = *(tok++);
	result_buf->s_port = htons((u_short) atoi(*(tok++)));
	result_buf->s_proto = *(tok++);
	result_buf->s_aliases = tok;
	*result = result_buf;
	ret = 0;
 DONE:
	__UCLIBC_MUTEX_UNLOCK(mylock);
 DONE_NOUNLOCK:
	errno = ret;
	return errno;
}
Пример #27
0
Файл: chord.c Проект: surki/hipl
/* initialize: set up sockets and such <yawn> */
void 
initialize(Server *srv)
{
    int flags;
    struct sockaddr_in sin, sout;

    setservent(1);

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(srv->node.port);
    sin.sin_addr.s_addr = htonl(INADDR_ANY);

    srv->in_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (srv->in_sock < 0)
	eprintf("socket failed:");
    
    if (bind(srv->in_sock, (struct sockaddr *) &sin, sizeof(sin)) < 0)
	eprintf("bind failed:");
	
    /* non-blocking i/o */
    flags = fcntl(srv->in_sock, F_GETFL);
    flags |= O_NONBLOCK;
    fcntl(srv->in_sock, F_SETFL, flags);

    /* outgoing socket */
    memset(&sout, 0, sizeof(sout));
    sout.sin_family = AF_INET;
    sout.sin_port = htons(0);
    sout.sin_addr.s_addr = htonl(INADDR_ANY);

    srv->out_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (srv->out_sock < 0)
	eprintf("socket failed:");

    if (bind(srv->out_sock, (struct sockaddr *) &sout, sizeof(sout)) < 0)
	eprintf("bind failed:");
}
Пример #28
0
_WCRTLINK struct servent *getservbyport( int port, const char *proto )
{
    struct servent *ret;

    if( port < 1 ) {
        _RWD_errno = EINVAL;
        return( NULL );
    }

    setservent( 1 );

    do {

        ret = getservent();

    } while( ret != NULL &&
             !( port == ret->s_port &&
               ( proto == NULL || SAFE_SAME_STR( proto, ret->s_proto ) ) ) );

    endservent();

    return( ret );
}
Пример #29
0
int main(int argc, char *argv[])
{
    char *hostname = NULL;
    struct protoent *p;
    struct protox *tp = NULL;	/* for printing cblocks & stats */
    int allprotos = 1;
    char *community = NULL;
    char *argp;
    struct snmp_session session;
    int dest_port = SNMP_PORT;
    int timeout = SNMP_DEFAULT_TIMEOUT;
    int version = SNMP_VERSION_1;
    int arg;

    init_mib();
    /*
     * Usage: snmpnetstatwalk -v 1 [-q] hostname community ...      or:
     * Usage: snmpnetstat [-v 2 ] [-q] hostname noAuth     ...
     */
    for(arg = 1; arg < argc; arg++){
	if (argv[arg][0] == '-'){
	    switch(argv[arg][1]){
              case 'V':
                fprintf(stderr,"UCD-snmp version: %s\n", VersionInfo);
                exit(0);
                break;

	      case 'h':
		usage();
		exit(0);

	      case 'd':
		snmp_set_dump_packet(1);
		break;

	      case 'q':
		snmp_set_quick_print(1);
		break;

	      case 'D':
                debug_register_tokens(&argv[arg][2]);
		snmp_set_do_debugging(1);
		break;
	      case 'p':
		if (argv[arg][2] != 0) dest_port = atoi(argv[arg]+2);
		else if (++arg == argc) {
		    usage();
		    exit(1);
		}
		else dest_port = atoi(argv[arg]);
		break;

	      case 't':
		if (argv[arg][2] != 0) timeout = atoi(argv[arg]+2);
		else if (++arg == argc) {
		    usage();
		    exit(1);
		}
		else timeout = atoi(argv[arg]);
		timeout *= 1000000;
		break;

	      case 'c':
		if (argv[arg][2] != 0) community = argv[arg]+2;
		else if (++arg == argc) {
		    usage();
		    exit(1);
		}
		else community = argv[arg];
		break;

	      case 'v':
		if (argv[arg][2] != 0) argp = argv[arg]+2;
		else if (arg == argc) {
		    usage();
		    exit(1);
		}
		else argp = argv[arg];
		if (!strcmp(argp,"1"))
		    version = SNMP_VERSION_1;
		else if (!strcmp(argp,"2c"))
		    version = SNMP_VERSION_2c;
		else {
		    fprintf(stderr, "Invalid version: %s\n", argp);
		    usage();
		    exit(1);
		}
		break;

	      case 'a':
		aflag++;
		break;

	      case 'i':
		iflag++;
		break;

	      case 'o':
		oflag++;
		break;

	      case 'n':
		nflag++;
		break;

	      case 'r':
		rflag++;
		break;

	      case 's':
		sflag++;
		break;

	      case 'P':
		if (++arg == argc) {
		    usage();
		    exit(1);
		}
		if ((tp = name2protox(argv [arg])) == NULLPROTOX) {
		  fprintf(stderr, "%s: unknown or uninstrumented protocol\n",
			  argv [arg]);
		  exit(1);
		}
		allprotos = 0;
		tp->pr_wanted = 1;
		break;

	      case 'I':
		iflag++;
		if (*(intrface = argv[arg] + 2) == 0) {
		  if (++arg == argc) {
		      usage();
		      exit(1);
		  }
		  if ((intrface = argv[arg]) == 0)
		    break;
		}
		break;

	      default:
		printf("invalid option: -%c\n", argv[arg][1]);
		break;
	    }
	    continue;
	}
	if (hostname == NULL){
	    hostname = argv[arg];
	} else if ((version == SNMP_VERSION_1 || version == SNMP_VERSION_2c)
                   && community == NULL){
	    community = argv[arg]; 
	} else if (isdigit(argv[arg][0])) {
            interval = atoi(argv[arg]);
            if (interval <= 0){
		usage();
		exit(1);
	    }
	    iflag++;
	} else {
	    usage();
	    exit(1);
	}
    }
    
    if (!hostname ||
	((version == SNMP_VERSION_1 || version == SNMP_VERSION_2c) && !community)) {
	usage();
	exit(1);
    }

    snmp_sess_init(&session);
    session.peername = hostname;
    session.remote_port = dest_port;
    session.timeout = timeout;
    if (version == SNMP_VERSION_1 || version == SNMP_VERSION_2c){
        session.version = version;
        session.community = (u_char *)community;
        session.community_len = strlen((char *)community);
    }

    SOCK_STARTUP;

    /* open an SNMP session */
    Session = snmp_open(&session);
    if (Session == NULL){
      /* diagnose snmp_open errors with the input struct snmp_session pointer */
        snmp_sess_perror("snmpnetstat", &session);
        SOCK_CLEANUP;
	exit(1);
    }

    /*
     * Keep file descriptors open to avoid overhead
     * of open/close on each call to get* routines.
     */
    sethostent(1);
    setnetent(1);
    setprotoent(1);
    setservent(1);

    if (iflag) {
	intpr(interval);
    }
    if (oflag) {
	intpro(interval);
    }
    if (rflag) {
	if (sflag)
	    rt_stats();
	else
	    routepr();
    }
    
    if (iflag || rflag || oflag)
	;
    else {

    while ((p = getprotoent46())) {
	for (tp = protox; tp->pr_name; tp++) {
	    if (strcmp(tp->pr_name, p->p_name) == 0)
		break;
	}
	if (tp->pr_name == 0 || (tp->pr_wanted == 0 && allprotos == 0))
	    continue;
	if (sflag) {
	    if (tp->pr_stats)
		(*tp->pr_stats)();
	} else
	    if (tp->pr_cblocks)
		(*tp->pr_cblocks)(tp->pr_name);
    }
    } /* ! iflag, rflag, oflag */

    endprotoent();
    endservent();
    endnetent();
    endhostent();

    snmp_close(Session);

    SOCK_CLEANUP;
    return 0;
}
Пример #30
0
int
main(int argc, char *argv[])
{
    char           *hostname = NULL;
    struct protoent *p;
    struct protox  *tp = NULL;  /* for printing cblocks & stats */
    int             allprotos = 1;
    char           *community = NULL;
    char           *argp;
    netsnmp_session session;
    int             timeout = SNMP_DEFAULT_TIMEOUT;
    int             version = SNMP_DEFAULT_VERSION;
    int             arg;

#ifndef DISABLE_MIB_LOADING
    init_mib();
#endif /* DISABLE_MIB_LOADING */
    /*
     * Usage: snmpnetstatwalk -v 1 [-q] hostname community ...      or:
     * Usage: snmpnetstat [-v 2 ] [-q] hostname noAuth     ...
     */
    while ((arg = getopt(argc, argv, "VhdqD:t:c:v:aionrsP:I:")) != EOF) {
        switch (arg) {
        case 'V':
            fprintf(stderr, "NET-SNMP version: %s\n",
                    netsnmp_get_version());
            exit(0);
            break;

        case 'h':
            usage();
            exit(0);

        case 'd':
            snmp_set_dump_packet(1);
            break;

        case 'q':
            snmp_set_quick_print(1);
            break;

        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;

        case 't':
            timeout = atoi(optarg);
            timeout *= 1000000;
            break;

        case 'c':
            community = optarg;
            break;

        case 'v':
            argp = optarg;
            version = -1;
#ifndef DISABLE_SNMPV1
            if (!strcasecmp(argp, "1"))
                version = SNMP_VERSION_1;
#endif
#ifndef DISABLE_SNMPV2C
            if (!strcasecmp(argp, "2c"))
                version = SNMP_VERSION_2c;
#endif
            if (version == -1) {
                fprintf(stderr, "Invalid version: %s\n", argp);
                usage();
                exit(1);
            }
            break;

        case 'a':
            aflag++;
            break;

        case 'i':
            iflag++;
            break;

        case 'o':
            oflag++;
            break;

        case 'n':
            nflag++;
            break;

        case 'r':
            rflag++;
            break;

        case 's':
            sflag++;
            break;

        case 'P':
            if ((tp = name2protox(optarg)) == NULLPROTOX) {
                fprintf(stderr, "%s: unknown or uninstrumented protocol\n",
                        optarg);
                exit(1);
            }
            allprotos = 0;
            tp->pr_wanted = 1;
            break;

        case 'I':
            iflag++;
            intrface = optarg;
            break;

        default:
            exit(1);
            break;
        }
        continue;
    }

    init_snmp("snmpapp");
    snmp_enable_stderrlog();
    if (version == SNMP_DEFAULT_VERSION) {
        version = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
		                     NETSNMP_DS_LIB_SNMPVERSION);
        if (!version) {
            switch (DEFAULT_SNMP_VERSION) {
#ifndef DISABLE_SNMPV1
            case 1:
                version = SNMP_VERSION_1;
                break;
#endif
#ifndef DISABLE_SNMPV2C
            case 2:
                version = SNMP_VERSION_2c;
                break;
#endif
            case 3:
                version = SNMP_VERSION_3;
                break;
            }
#ifndef DISABLE_SNMPV1
        } else if (version == NETSNMP_DS_SNMP_VERSION_1) {
                          /* Bogus value. version1 = 0 */
            version = SNMP_VERSION_1;
#endif
        }
    }
    if (optind < argc) {
        hostname = argv[optind++];
    }
    else {
        fprintf(stderr, "Missing host name.\n");
        exit(1);
    }
    if (community == NULL) {
	community = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
		                          NETSNMP_DS_LIB_COMMUNITY);
    }
    if (optind < argc && isdigit(argv[optind][0])) {
        interval = atoi(argv[optind++]);
        if (interval <= 0) {
            usage();
            exit(1);
        }
        iflag++;
    }
    if (optind < argc) {
        usage();
        exit(1);
    }


    snmp_sess_init(&session);
    session.peername = hostname;
    session.timeout = timeout;
#if !defined(DISABLE_SNMPV1) || !defined(DISABLE_SNMPV2C)
    if (version != SNMP_VERSION_3) {
        if (!community) {
            fprintf(stderr, "Missing community name.\n");
            exit(1);
        }
        session.version = version;
        session.community = (u_char *) community;
        session.community_len = strlen(community);
    }
#endif

    SOCK_STARTUP;

    /*
     * open an SNMP session 
     */
    Session = snmp_open(&session);
    if (Session == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpnetstat", &session);
        SOCK_CLEANUP;
        exit(1);
    }

    /*
     * Keep file descriptors open to avoid overhead
     * of open/close on each call to get* routines.
     */
    sethostent(1);
    setnetent(1);
    setprotoent(1);
    setservent(1);

    if (iflag) {
        intpr(interval);
    }
    if (oflag) {
        intpro(interval);
    }
    if (rflag) {
        if (sflag)
            rt_stats();
        else
            routepr();
    }

    if (!(iflag || rflag || oflag)) {
        while ((p = getprotoent46())) {
            for (tp = protox; tp->pr_name; tp++) {
                if (strcmp(tp->pr_name, p->p_name) == 0)
                    break;
            }
            if (tp->pr_name == 0 || (tp->pr_wanted == 0 && allprotos == 0))
                continue;
            if (sflag) {
                if (tp->pr_stats)
                    (*tp->pr_stats) ();
            } else if (tp->pr_cblocks)
                (*tp->pr_cblocks) (tp->pr_name);
        }
    }                           /* ! iflag, rflag, oflag */

    endprotoent();
    endservent();
    endnetent();
    endhostent();

    snmp_close(Session);

    SOCK_CLEANUP;
    return 0;
}