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

C++ FD_SET函数代码示例

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

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



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

示例1: main

int main() {

	fd_set master;

	/* temp file descriptor list for select() */
	fd_set read_fds;
	fd_set write_fds;

	struct sockaddr_in serv_addr, cli_addr;
	int sockfd, newsockfd, fdmax, i;   /* int fdmax is the maximum file descriptor number */
	socklen_t clilen;

	char buf[1024];

	/* clear the master and temp sets */

	FD_ZERO(&master);

	FD_ZERO(&read_fds);

	FD_ZERO(&write_fds);


	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		perror("socket");

	/* bind */
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(1234);

	if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
		perror("bind");


	listen(sockfd, 10);
	clilen = sizeof(cli_addr);

	/* add the sockfd to the master set */
	FD_SET(sockfd, &master);

	/* keep track of the biggest file descriptor */
	fdmax = sockfd; /* so far, it's this one*/


	/*Main loop */
	for( ; ; ) {

	/* copy it */
		read_fds = master;
		write_fds = master;
		struct timeval tv;
		tv.tv_sec = 1;
		tv.tv_usec = 0;

		if(select(fdmax+1, &read_fds, &write_fds, NULL, NULL) < 0)
			perror("select");

		/*run through the existing connections looking for data to be read*/
		if(fdmax >= OPEN_MAX){
			perror("open_max");
			return 1;
		}
		for(i = 0; i <= fdmax; i++) {
			if(FD_ISSET(i, &read_fds)) {  /* we got one... */
				printf("Server %d: read\n", i);
					if(i == sockfd) {

						if((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) < 0)
							perror("accept");

						FD_SET(newsockfd, &master); /* add to master set */
						printf("Server %d: accept new client %d\n", i, newsockfd);
						/* keep track of the maximum */
						fd[newsockfd] = -1;
						if(newsockfd > fdmax) {
							fdmax = newsockfd;
						}
					}
					else {
						/* handle data from a client */
						memset(buf, 0, sizeof buf);
						int size;
						if((size = recv(i, buf, 1024, 0)) <= 0) {
							continue;
						}
						else {
							/* we got some data from a client*/
							printf("Server %d: path %s\n", i, buf);
							fd[i] = open(buf, O_RDONLY);
							printf("Server %d: file desc %d\n", i, fd[i]);
							if(fd[i] < 0){
								memset(buf, 0, sizeof buf);
								memcpy(buf,"file not exist", 14);
								close(fd[i]);
								if(send(i, buf, 1024, 0) < 0)
									perror("send");
								printf("Server %d: %s\n", i, buf);
								close(i);
//.........这里部分代码省略.........
开发者ID:pbondarenko,项目名称:testrepository,代码行数:101,代码来源:server.c


示例2: main

int main(int argc, char *argv[])
{
	struct sockaddr_in broadcast_adrs;
	struct sockaddr_in from_adrs;
	socklen_t from_len;

	int sock, count = 0;
	int broadcast_sw = 1;
	fd_set mask, readfds;
	struct timeval timeout;

	int port = DEFAULT_PORT;
	char username[L_USERNAME] = "JohnDou";

	char s_buf[S_BUFSIZE], r_buf[R_BUFSIZE];
	int strsize = 0;
	packet r_packet;

	/* コマンドライン引数のチェックおよび使用法の表示 */
	if(argc != 3)
	{
		fprintf(stderr, "Usage: %s User_name, Port_number\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	sprintf(username, "%s", argv[1]);
	port = atoi(argv[2]);
	set_sockaddr_in_broadcast(&broadcast_adrs, (in_port_t)port);
	sock = init_udpclient();

	if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *)&broadcast_sw, sizeof(broadcast_sw)) == 1)
	{
		exit_errmesg("setsockopt()");
	}

	FD_ZERO(&mask);
	FD_SET(sock, &mask);
	// s_buf にHELLOパケットを格納
	create_packet(HELLO, s_buf);
	strsize = sizeof(s_buf);

	int i;
	for(i = 0; i < 3; i++)
	{
		Sendto(sock, s_buf, strsize, 0, (struct sockaddr *)&broadcast_adrs, sizeof(broadcast_adrs));

		readfds = mask;
		timeout.tv_sec = TIMEOUT_SEC;
		timeout.tv_usec = 0;

		if(select(sock+1, &readfds, NULL, NULL, &timeout) == 0)
		{
			count++;
			printf("Send HELLO packets %d times.\n", count);
			printf("pct : %s\n", s_buf);
			if(count == 3)
			{
				printf("There are no server, so you are server.\n");
				server(username, port);
			}
			continue;
		}

		// HEREパケットを受信したときの処理
		from_len = sizeof(from_adrs);
		strsize = Recvfrom(sock, r_buf, R_BUFSIZE-1, 0, (struct sockaddr *)&from_adrs, &from_len);
		r_packet = re_packet(r_buf);

		if(analize_header(r_packet.header) == HERE)
		{
			printf("There are server, so you are client.\n");
			client(username, from_adrs);
		}
	}

	return 0;
}
开发者ID:kichamura,项目名称:ex05,代码行数:77,代码来源:water_cooler.c


示例3: server_init


//.........这里部分代码省略.........
    if (l2sock < 0) {
        log_crit("Could not create L2CAP socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        return (-1);
    }

    size = sizeof(imtu);
    if (getsockopt(l2sock, SOL_L2CAP, SO_L2CAP_IMTU, &imtu, &size) < 0) {
        log_crit("Could not get L2CAP IMTU. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    memset(&l2, 0, sizeof(l2));
    l2.l2cap_len = sizeof(l2);
    l2.l2cap_family = AF_BLUETOOTH;
    memcpy(&l2.l2cap_bdaddr, NG_HCI_BDADDR_ANY, sizeof(l2.l2cap_bdaddr));
    l2.l2cap_psm = htole16(NG_L2CAP_PSM_SDP);

    if (bind(l2sock, (struct sockaddr *) &l2, sizeof(l2)) < 0) {
        log_crit("Could not bind L2CAP socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    if (listen(l2sock, 10) < 0) {
        log_crit("Could not listen on L2CAP socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /* Allocate incoming buffer */
    srv->imtu = (imtu > SDP_LOCAL_MTU)? imtu : SDP_LOCAL_MTU;
    srv->req = (uint8_t *) calloc(srv->imtu, sizeof(srv->req[0]));
    if (srv->req == NULL) {
        log_crit("Could not allocate request buffer");
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /* Allocate memory for descriptor index */
    srv->fdidx = (fd_idx_p) calloc(FD_SETSIZE, sizeof(srv->fdidx[0]));
    if (srv->fdidx == NULL) {
        log_crit("Could not allocate fd index");
        free(srv->req);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /* Register Service Discovery profile (attach it to control socket) */
    if (provider_register_sd(unsock) < 0) {
        log_crit("Could not register Service Discovery profile");
        free(srv->fdidx);
        free(srv->req);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /*
     * If we got here then everything is fine. Add both control sockets
     * to the index.
     */

    FD_ZERO(&srv->fdset);
    srv->maxfd = (unsock > l2sock)? unsock : l2sock;

    FD_SET(unsock, &srv->fdset);
    srv->fdidx[unsock].valid = 1;
    srv->fdidx[unsock].server = 1;
    srv->fdidx[unsock].control = 1;
    srv->fdidx[unsock].priv = 0;
    srv->fdidx[unsock].rsp_cs = 0;
    srv->fdidx[unsock].rsp_size = 0;
    srv->fdidx[unsock].rsp_limit = 0;
    srv->fdidx[unsock].omtu = SDP_LOCAL_MTU;
    srv->fdidx[unsock].rsp = NULL;

    FD_SET(l2sock, &srv->fdset);
    srv->fdidx[l2sock].valid = 1;
    srv->fdidx[l2sock].server = 1;
    srv->fdidx[l2sock].control = 0;
    srv->fdidx[l2sock].priv = 0;
    srv->fdidx[l2sock].rsp_cs = 0;
    srv->fdidx[l2sock].rsp_size = 0;
    srv->fdidx[l2sock].rsp_limit = 0;
    srv->fdidx[l2sock].omtu = 0; /* unknown */
    srv->fdidx[l2sock].rsp = NULL;

    return (0);
}
开发者ID:ppaeps,项目名称:freebsd-head,代码行数:101,代码来源:server.c


示例4: SLPNetworkSendMessage

/*=========================================================================*/ 
int SLPNetworkSendMessage(int sockfd,
                          SLPBuffer buf,
                          struct sockaddr_in* peeraddr,
                          struct timeval* timeout)
/* Sends a message                                                         */
/*                                                                         */
/* Returns  -  zero on success non-zero on failure                         */
/*                                                                         */
/* errno         EPIPE error during write                                  */
/*               ETIME read timed out                                      */
/*=========================================================================*/ 
{
    fd_set      writefds;
    int         xferbytes;
    int         flags = 0;

#if defined(MSG_NOSIGNAL)
    flags = MSG_NOSIGNAL;
#endif
    
    buf->curpos = buf->start;
    
    while(buf->curpos < buf->end)
    {
        FD_ZERO(&writefds);
        FD_SET(sockfd, &writefds);

        xferbytes = select(sockfd + 1, 0, &writefds, 0, timeout);
        if(xferbytes > 0)
        {
            xferbytes = sendto(sockfd,
                               buf->curpos, 
                               buf->end - buf->curpos, 
                               flags,
                               (struct sockaddr *)peeraddr,
                               sizeof(struct sockaddr_in));
            
            if(xferbytes > 0)
            {
                buf->curpos = buf->curpos + xferbytes;
            }
            else
            {
#ifndef WIN32
                errno = EPIPE;
#endif
                return -1;
            }
        }
        else if(xferbytes == 0)
        {
            /* timed out */
#ifndef WIN32
            errno = ETIME;
#endif
            return -1;
        }
        else
        {
#ifndef WIN32
            errno = EPIPE;
#endif
            return -1;
        }
    }
    
    return 0;
}
开发者ID:ncultra,项目名称:openslp,代码行数:69,代码来源:slp_network.c


示例5: do_cmd

void do_cmd(comedi_t *dev,comedi_cmd *cmd)
{
	int total=0;
	int ret;
	int go;
	fd_set rdset;
	struct timeval timeout;

	ret=comedi_command_test(dev,cmd);

	printf("test ret=%d\n",ret);
	if(ret<0){
		printf("errno=%d\n",errno);
		comedi_perror("comedi_command_test");
		return;
	}

	dump_cmd(stdout,cmd);

	ret=comedi_command_test(dev,cmd);

	printf("test ret=%d\n",ret);
	if(ret<0){
		printf("errno=%d\n",errno);
		comedi_perror("comedi_command_test");
		return;
	}

	dump_cmd(stdout,cmd);

	comedi_set_read_subdevice(dev, cmd->subdev);
	ret = comedi_get_read_subdevice(dev);
	if (ret < 0 || ret != cmd->subdev) {
		fprintf(stderr,
			"failed to change 'read' subdevice from %d to %d\n",
			ret, cmd->subdev);
		return;
	}

	ret=comedi_command(dev,cmd);

	printf("ret=%d\n",ret);
	if(ret<0){
		printf("errno=%d\n",errno);
		comedi_perror("comedi_command");
		return;
	}

	go=1;
	while(go){
		FD_ZERO(&rdset);
		FD_SET(comedi_fileno(device),&rdset);
		timeout.tv_sec = 0;
		timeout.tv_usec = 50000;
		ret = select(comedi_fileno(dev)+1,&rdset,NULL,NULL,&timeout);
		//printf("select returned %d\n",ret);
		if(ret<0){
			perror("select");
		}else if(ret==0){
			/* hit timeout */
			printf("timeout, polling...\n");
			ret = comedi_poll(device,cmd->subdev);
			printf("poll returned %d\n",ret);
		}else if(FD_ISSET(comedi_fileno(device),&rdset)){
			/* comedi file descriptor became ready */
			//printf("comedi file descriptor ready\n");
			ret=read(comedi_fileno(dev),buf,sizeof(buf));
			printf("read returned %d\n",ret);
			if(ret<0){
				if(errno==EAGAIN){
					go = 0;
					perror("read");
				}
			}else if(ret==0){
				go = 0;
			}else{
				int i;
				total+=ret;
				//printf("read %d %d\n",ret,total);
				for(i=0;i<ret/sizeof(sampl_t);i++){
					printf("%d\n",buf[i]);
				}
			}
		}else{
			/* unknown file descriptor became ready */
			printf("unknown file descriptor ready\n");
		}
	}
}
开发者ID:olsonse,项目名称:comedilib,代码行数:89,代码来源:poll.c


示例6: ourIPAddress

netAddressBits ourIPAddress(UsageEnvironment& env) {
  static netAddressBits ourAddress = 0;
  int sock = -1;
  struct in_addr testAddr;

  if (ReceivingInterfaceAddr != INADDR_ANY) {
    // Hack: If we were told to receive on a specific interface address, then 
    // define this to be our ip address:
    ourAddress = ReceivingInterfaceAddr;
  }

  if (ourAddress == 0) {
    // We need to find our source address
    struct sockaddr_in fromAddr;
    fromAddr.sin_addr.s_addr = 0;

    // Get our address by sending a (0-TTL) multicast packet,
    // receiving it, and looking at the source address used.
    // (This is kinda bogus, but it provides the best guarantee
    // that other nodes will think our address is the same as we do.)
    do {
      loopbackWorks = 0; // until we learn otherwise

      testAddr.s_addr = our_inet_addr("228.67.43.91"); // arbitrary
      Port testPort(15947); // ditto

      sock = setupDatagramSocket(env, testPort);
      if (sock < 0) break;

      if (!socketJoinGroup(env, sock, testAddr.s_addr)) break;

      unsigned char testString[] = "hostIdTest";
      unsigned testStringLength = sizeof testString;

      if (!writeSocket(env, sock, testAddr, testPort.num(), 0,
		       testString, testStringLength)) break;

      // Block until the socket is readable (with a 5-second timeout):
      fd_set rd_set;
      FD_ZERO(&rd_set);
      FD_SET((unsigned)sock, &rd_set);
      const unsigned numFds = sock+1;
      struct timeval timeout;
      timeout.tv_sec = 5;
      timeout.tv_usec = 0;
      int result = select(numFds, &rd_set, NULL, NULL, &timeout);
      if (result <= 0) break;

      unsigned char readBuffer[20];
      int bytesRead = readSocket(env, sock,
				 readBuffer, sizeof readBuffer,
				 fromAddr);
      if (bytesRead != (int)testStringLength
	  || strncmp((char*)readBuffer, (char*)testString, testStringLength) != 0) {
	break;
      }

      // We use this packet's source address, if it's good:
      loopbackWorks = !badAddressForUs(fromAddr.sin_addr.s_addr);
    } while (0);

    if (sock >= 0) {
      socketLeaveGroup(env, sock, testAddr.s_addr);
      closeSocket(sock);
    }

    if (!loopbackWorks) do {
      // We couldn't find our address using multicast loopback,
      // so try instead to look it up directly - by first getting our host name, and then resolving this host name
      char hostname[100];
      hostname[0] = '\0';
      int result = gethostname(hostname, sizeof hostname);
      if (result != 0 || hostname[0] == '\0') {
	env.setResultErrMsg("initial gethostname() failed");
	break;
      }

      // Try to resolve "hostname" to an IP address:
      NetAddressList addresses(hostname);
      NetAddressList::Iterator iter(addresses);
      NetAddress const* address;

      // Take the first address that's not bad:
      netAddressBits addr = 0;
      while ((address = iter.nextAddress()) != NULL) {
	netAddressBits a = *(netAddressBits*)(address->data());
	if (!badAddressForUs(a)) {
	  addr = a;
	  break;
	}
      }

      // Assign the address that we found to "fromAddr" (as if the 'loopback' method had worked), to simplify the code below: 
      fromAddr.sin_addr.s_addr = addr;
    } while (0);

    // Make sure we have a good address:
    netAddressBits from = fromAddr.sin_addr.s_addr;
    if (badAddressForUs(from)) {
      char tmp[100];
//.........这里部分代码省略.........
开发者ID:HardikSangani,项目名称:sandbox_live,代码行数:101,代码来源:GroupsockHelper.cpp


示例7: IPv4_UDP

int IPv4_UDP(const char *pcListen_address, const int iPort)
{
    int listen_socket = 0;
    listen_socket = Network_Listen4UDP(pcListen_address, iPort);
    if (listen_socket < 0)
    {
        daemon_log(LOG_ERR, "Failed to bind");
        return -1;
    }

    while (1)
    {
        struct timeval tv;
        fd_set readfds;
        tsConectionMapping *psConnectionMapping = psConnectionMappingHead;
        int max_fd = 0;

        tv.tv_sec = 2;
        tv.tv_usec = 0;

        FD_ZERO(&readfds);
        FD_SET(listen_socket, &readfds);
        max_fd = listen_socket;
        
        while (psConnectionMapping)
        {
            if (psConnectionMapping->iIPv6Socket > max_fd)
            {
                max_fd = psConnectionMapping->iIPv6Socket;
            }
            
            FD_SET(psConnectionMapping->iIPv6Socket, &readfds);
            
            psConnectionMapping = psConnectionMapping->psNext;
        }

        select(max_fd+1, &readfds, NULL, NULL, &tv);

        if (FD_ISSET(listen_socket, &readfds))
        {
            handle_incoming_ipv4_packet(listen_socket);
        }
        else
        {
            struct timeval sTimeNow;
            gettimeofday(&sTimeNow, NULL);
            
            psConnectionMapping = psConnectionMappingHead;
            
            while (psConnectionMapping)
            {
                if (FD_ISSET(psConnectionMapping->iIPv6Socket, &readfds))
                {
                    handle_incoming_ipv6_packet(listen_socket, psConnectionMapping);
                }
                
                if (sTimeNow.tv_sec > (psConnectionMapping->sLastPacketTime.tv_sec + UDP_Connection_Timeout))
                {
                    if (verbosity >= LOG_DEBUG)
                    {
                        daemon_log(LOG_DEBUG, "Deleting client: %d seconds since last data", UDP_Connection_Timeout);
                    }
                    psConnectionMapping = psDeleteMapping (psConnectionMapping);
                }
                else
                {
                    psConnectionMapping = psConnectionMapping->psNext;
                }
            }
        }

    }

    return 0;
}
开发者ID:WRTIOT,项目名称:JIPd,代码行数:75,代码来源:IPv4_UDP.c


示例8: main

int main(void)
{
    static int fd[MAX_PAR]; /* to force initialization */
    struct sockaddr_atmsvc local[MAX_ADDR];
    struct atmif_sioc req;
    struct atm_sap sap;
    struct atm_qos qos;
    int listen_fd;
    fd_set rset,wset;
    int fds,completed = 0,connects = 0,accepts = 0;

    FD_ZERO(&rset);
    FD_ZERO(&wset);
    if (text2sap(SAP,&sap,0) < 0) {
	fprintf(stderr,"text2sap\n");
	return 1;
    }
    if (text2qos(QOS,&qos,0) < 0) {
	fprintf(stderr,"text2qos\n");
	return 1;
    }
    listen_fd = socket(PF_ATMSVC,SOCK_DGRAM,0);
    if (listen_fd < 0) {
	perror("socket");
	return 1;
    }
    req.number = ITF;
    req.arg = local;
    req.length = sizeof(local);
    if (ioctl(listen_fd,ATM_GETADDR,&req) < 0) {
	perror("ioctl");
	return 1;
    }
    if (!req.length) {
	fprintf(stderr,"No local address\n");
	return 1;
    }
    if (setsockopt(listen_fd,SOL_ATM,SO_ATMSAP,&sap,sizeof(sap)) < 0) {
	perror("setsockopt SO_ATMSAP");
	return 1;
    }
    if (setsockopt(listen_fd,SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0) {
	perror("setsockopt SO_ATMQOS");
	return 1;
    }
    if (bind(listen_fd,(struct sockaddr *) local,sizeof(*local)) < 0) {
	perror("bind");
	return 1;
    }
    if (fcntl(listen_fd,F_SETFL,O_NONBLOCK) < 0) {
	perror("fnctl");
	return 1;
    }
    if (listen(listen_fd,5) < 0) {
	perror("listen");
	return 1;
    }
    FD_SET(listen_fd,&rset);
    fds = listen_fd+1;
    (void) signal(SIGCHLD,SIG_IGN);
    while (1) {
	static struct timeval no_delay;
	fd_set _rset = rset;
	fd_set _wset = wset;
	int ret,i,empty;

	no_delay.tv_sec = 0;
	no_delay.tv_usec = 100000;
	ret = select(fds,&_rset,&_wset,NULL,&no_delay);
	if (ret < 0) {
	    perror("select");
	    return 1;
	}
	if (FD_ISSET(listen_fd,&_rset)) {
	    pid_t pid;

	    pid = fork();
	    if (pid < 0) {
		perror("fork");
		return 1;
	    }
	    if (!pid) {
		if (accept(listen_fd,NULL,NULL) >= 0) exit(0);
		perror("accept");
		return 1;
	    }
	    accepts++;
	}
	empty = -1;
	for (i = 0; i < MAX_PAR; i++)
	    if (!fd[i]) empty = i;
	    else if (FD_ISSET(fd[i],&_wset)) {
		    struct sockaddr_atmsvc dummy;

		    if (connect(fd[i],(struct sockaddr *) &dummy,sizeof(dummy))
		      < 0) {
			perror("connect");
			return 1;
		    }
		    FD_CLR(fd[i],&wset);
//.........这里部分代码省略.........
开发者ID:FelipeFernandes1988,项目名称:Alice-1121-Modem,代码行数:101,代码来源:svctor.c


示例9: connecthostport

/* connecthostport()
 * return a socket connected (TCP) to the host and port
 * or -1 in case of error */
int connecthostport(const char * host, unsigned short port,
                    unsigned int scope_id)
{
	int s, n;
#ifdef USE_GETHOSTBYNAME
	struct sockaddr_in dest;
	struct hostent *hp;
#else /* #ifdef USE_GETHOSTBYNAME */
	char tmp_host[MAXHOSTNAMELEN+1];
	char port_str[8];
	struct addrinfo *ai, *p;
	struct addrinfo hints;
#endif /* #ifdef USE_GETHOSTBYNAME */
#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT
	struct timeval timeout;
#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */

#ifdef USE_GETHOSTBYNAME
	hp = gethostbyname(host);
	if(hp == NULL)
	{
		herror(host);
		return -1;
	}
	memcpy(&dest.sin_addr, hp->h_addr, sizeof(dest.sin_addr));
	memset(dest.sin_zero, 0, sizeof(dest.sin_zero));
	s = socket(PF_INET, SOCK_STREAM, 0);
	if(s < 0)
	{
		PRINT_SOCKET_ERROR("socket");
		return -1;
	}
#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT
	/* setting a 3 seconds timeout for the connect() call */
	timeout.tv_sec = 3;
	timeout.tv_usec = 0;
	if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0)
	{
		PRINT_SOCKET_ERROR("setsockopt");
	}
	timeout.tv_sec = 3;
	timeout.tv_usec = 0;
	if(setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)) < 0)
	{
		PRINT_SOCKET_ERROR("setsockopt");
	}
#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */
	dest.sin_family = AF_INET;
	dest.sin_port = htons(port);
	n = connect(s, (struct sockaddr *)&dest, sizeof(struct sockaddr_in));
#ifdef MINIUPNPC_IGNORE_EINTR
	while(n < 0 && errno == EINTR)
	{
		socklen_t len;
		fd_set wset;
		int err;
		FD_ZERO(&wset);
		FD_SET(s, &wset);
		if((n = select(s + 1, NULL, &wset, NULL, NULL)) == -1 && errno == EINTR)
			continue;
		/*len = 0;*/
		/*n = getpeername(s, NULL, &len);*/
		len = sizeof(err);
		if(getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len) < 0) {
			PRINT_SOCKET_ERROR("getsockopt");
			closesocket(s);
			return -1;
		}
		if(err != 0) {
			errno = err;
			n = -1;
		}
	}
#endif /* #ifdef MINIUPNPC_IGNORE_EINTR */
	if(n<0)
	{
		PRINT_SOCKET_ERROR("connect");
		closesocket(s);
		return -1;
	}
#else /* #ifdef USE_GETHOSTBYNAME */
	/* use getaddrinfo() instead of gethostbyname() */
	memset(&hints, 0, sizeof(hints));
	/* hints.ai_flags = AI_ADDRCONFIG; */
#ifdef AI_NUMERICSERV
	hints.ai_flags = AI_NUMERICSERV;
#endif
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */
	/* hints.ai_protocol = IPPROTO_TCP; */
	snprintf(port_str, sizeof(port_str), "%hu", port);
	if(host[0] == '[')
	{
		/* literal ip v6 address */
		int i, j;
		for(i = 0, j = 1; host[j] && (host[j] != ']') && i < MAXHOSTNAMELEN; i++, j++)
		{
//.........这里部分代码省略.........
开发者ID:FlavioFalcao,项目名称:tinq-core,代码行数:101,代码来源:connecthostport.c


示例10: sprintf

/*
Open up UART port and begin redirect input/output from login shell.
*/
void *ttyS(char *port)
{
   struct termios term,stdIn,stdOut;
   fd_set rset;
   int fd, maxfd,selectval,nbytes;
   int sd=STDIN_FILENO;
   char buf[TRANSFER_BUFFER_SIZE];
   char devname[40];

  int ch,lastchar;
   /* connect to tty device write port */
   sprintf(devname,"/dev/tty%s",port);
   if( (fd=open(devname,O_RDWR | O_NOCTTY |O_NDELAY)) < 0 ){
	  fprintf(stderr,"can't open device %s\n",devname);
     return NULL;
   }
#ifdef DEBUG
   fprintf(stderr,"%s opened, fd=%d\n",devname,fd);
#endif   
   hndl =fd;
   fcntl(fd,F_SETFL,O_NONBLOCK); /* set non-blocking mode */
   if (tcgetattr(fd,&term) ){
      fprintf(stderr,"Can't get device attr.\n");
      close(fd);
      return NULL;
   }
   saved_termios = term; //save original termios
   if(signal(SIGINT,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGINT handler\n");
      close(fd);
      return NULL;
   }
   if(signal(SIGTERM,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGTERM handler\n");
      close(fd);
      return NULL;
   }
   if(signal(SIGHUP,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGHUP handler\n");
      close(fd);
      return NULL;
   }
    /* make the following file descriptors raw */
   
    if (isatty (0)) {
       tcgetattr(0,   &original_stdin);
       tcgetattr(1,   &original_stdout);
       tty_modified = 1;
       stdIn = original_stdin;
       stdOut = original_stdout;
       MAKE_TTY_RAW(0,  original_stdin);
       MAKE_TTY_RAW(1,  original_stdout);
    }
    
   cfmakeraw(&term);	/* raw mode */
   atexit(cleanup);

   cfsetispeed(&term,B115200); //B9600);
   cfsetospeed(&term,B115200); //B9600);
   tcsetattr(fd,TCSANOW,&term);
#ifdef DEBUG
   if (!tcgetattr(fd,&term) ){
	fprintf(stderr,"tty: ispeed=%d, ospeed = %d\n",\
	cfgetispeed(&term),cfgetospeed(&term));
    }
#endif    
   set_noecho(fd);
   set_noecho(STDOUT_FILENO);
   
#ifdef DEBUG
   if (!tcgetattr(STDIN_FILENO,&stdIn) ){
	fprintf(stderr,"STDIN: ispeed=%d, ospeed = %d\n",\
	cfgetispeed(&stdIn),cfgetospeed(&stdIn));
    }
#endif
   tcflush(fd,TCIOFLUSH);
   maxfd = ((sd > fd) ? sd:fd)+1;
  /*
   * Loop to read/write between remote client and host until 'esc  q' is received. 
   */
  for (;;)
    {
     FD_ZERO(&rset); 
      FD_SET (STDIN_FILENO, &rset);
      FD_SET (fd, &rset);
      selectval = select (maxfd, &rset, NULL, NULL, NULL);
      if (selectval == -1)
		{
		  syslog (LOG_ERR, "select(): %m");
		  break;
		}
      
      /*
	   * if client is readable, read from client, write to destination 
       */
      if (FD_ISSET (STDIN_FILENO, &rset))
		{
//.........这里部分代码省略.........
开发者ID:souktha,项目名称:tty2comport,代码行数:101,代码来源:tty2comport.c


示例11: main


//.........这里部分代码省略.........
		len = sizeof(curfreq);
		if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
			if (vflag)
				warn("error reading current CPU frequency");
		}
		if (curfreq < freqs[numfreqs - 1]) {
			if (vflag) {
				printf("CPU frequency is below user-defined "
				    "minimum; changing frequency to %d "
				    "MHz\n", freqs[numfreqs - 1]);
			}
			if (set_freq(freqs[numfreqs - 1]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[numfreqs - 1]);
			}
		} else if (curfreq > freqs[0]) {
			if (vflag) {
				printf("CPU frequency is above user-defined "
				    "maximum; changing frequency to %d "
				    "MHz\n", freqs[0]);
			}
			if (set_freq(freqs[0]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[0]);
			}
		}
	}

	idle = 0;
	/* Main loop. */
	for (;;) {
		FD_ZERO(&fdset);
		if (devd_pipe >= 0) {
			FD_SET(devd_pipe, &fdset);
			nfds = devd_pipe + 1;
		} else {
			nfds = 0;
		}
		if (mode == MODE_HIADAPTIVE || idle < 120)
			to = poll_ival;
		else if (idle < 360)
			to = poll_ival * 2;
		else
			to = poll_ival * 4;
		timeout.tv_sec = to / 1000000;
		timeout.tv_usec = to % 1000000;
		select(nfds, &fdset, NULL, &fdset, &timeout);

		/* If the user requested we quit, print some statistics. */
		if (exit_requested) {
			if (vflag && mjoules_used != 0)
				printf("total joules used: %u.%03u\n",
				    (u_int)(mjoules_used / 1000),
				    (int)mjoules_used % 1000);
			break;
		}

		/* Read the current AC status and record the mode. */
		acline_read();
		switch (acline_status) {
		case SRC_AC:
			mode = mode_ac;
			break;
		case SRC_BATTERY:
			mode = mode_battery;
			break;
开发者ID:coyizumi,项目名称:cs111,代码行数:67,代码来源:powerd.c


示例12: sendTest

void
sendTest(int sockFD, int delay, int reqOOB, int size)
{
    char *buf, *bufTest;
    fd_set *rfds, *wfds, *efds;
    int i, j;
    int nbytes, code;
    selcmd_t selCmd;
    time_t stime, etime;

    buf = (char *)malloc(size);
    assert(buf);
    bufTest = (char *)malloc(size);
    assert(bufTest);

    for (j = i = 0; i < size; i++, j++) {
	if (j == END_DATA)
	    j++;
	if (j > 255)
	    j = 0;
	buf[i] = (char)j;
    }

    selCmd.sc_cmd = SC_WRITE;
    selCmd.sc_info = size;
    selCmd.sc_delay = delay;
    selCmd.sc_flags = SC_WAIT_ONLY;

    nbytes = write(sockFD, (char *)&selCmd, sizeof(selCmd));
    assert(nbytes == sizeof(selCmd));

    Log("Starting to write %d bytes.\n", size);
    if (!delay) {
	nbytes = write(sockFD, buf, size);
	assert(nbytes == size);
    } else {
	rfds = IOMGR_AllocFDSet();
	wfds = IOMGR_AllocFDSet();
	efds = IOMGR_AllocFDSet();
	if (!rfds || !wfds || !efds) {
	    printf("%s: Could not allocate all fd_sets.\n", program);
	    exit(1);
	}

	for (writeIndex = i = 0; i < size; writeIndex++, i++) {
	    FD_ZERO(rfds);
	    FD_ZERO(wfds);
	    FD_ZERO(efds);
	    FD_SET(sockFD, wfds);
	    FD_SET(sockFD, efds);
	    (void)time(&stime);
	    code =
		IOMGR_Select(sockFD + 1, rfds, wfds, efds,
			     (struct timeval *)NULL);
	    assert(code > 0);

	    if (FD_ISSET(sockFD, wfds)) {
		(void)time(&etime);
		if (etime - stime > 1) {
		    Log("Waited %d seconds to write at offset %d.\n",
			etime - stime, i);
		}
		stime = etime;
		nbytes = write(sockFD, &buf[i], 1);
		(void)time(&etime);
		if (etime - stime > 1) {
		    Log("Waited %d seconds IN write.\n", etime - stime);
		}
		assert(nbytes == 1);
		FD_CLR(sockFD, wfds);
	    }
	    assertNullFDSet(0, rfds);
	    assertNullFDSet(0, wfds);
	    assertNullFDSet(0, efds);
	}
    }

    Log("Wrote %d bytes.\n", size);
    i = 0;
    while (i < size) {
	nbytes = read(sockFD, &bufTest[i], size);
	i += nbytes;
    }
    Log("Read %d bytes.\n", size);

    assert(memcmp(buf, bufTest, size) == 0);
    Log("Compared %d bytes.\n", size);
}
开发者ID:maxendpoint,项目名称:openafs_cvs,代码行数:88,代码来源:selclient.c


示例13: dispatch

void dispatch(int rtSocket, int pgSocket, int pfpSocket) {
	fd_set set;
	int maxfd;
	struct timeval tv;	
	void* buf = malloc(MAXLINE);
	SockAddrIn senderAddr;	
	int addrLen = sizeof(senderAddr),
	res = 0;

	debug("Gonna listen to rtsocket: %d", rtSocket);
	for(;;){
		if (endOfTour == 0) {
			tv.tv_sec = 20;
		} 
		else {
			tv.tv_sec = 5;			
		}
		
		tv.tv_usec = 0;
		FD_ZERO(&set);
		FD_SET(rtSocket, &set);
		FD_SET(pgSocket, &set);
		maxfd = max(rtSocket, pgSocket);
		if (mcastRecvSd > 0) {
			FD_SET(mcastRecvSd, &set);
			maxfd = max(maxfd, mcastRecvSd);
		}
		res = select(maxfd + 1, &set, NULL, NULL, &tv);
		if (res == 0) {
			if (endOfTour == 1) {
				printf("Auf Wiedersehen!\n");
				return;
			}
			debug("Nothing read. Timeout.");				
			continue;
		}
		
		// if received a rt
		if(FD_ISSET(rtSocket, &set)){
			// let's choose some smaller value than 1500 bytes.
			bzero(buf, MAXLINE);
			bzero(&senderAddr, addrLen);
		 	addrLen = sizeof(senderAddr);
			int length = recvfrom(rtSocket, buf, MAXLINE, 0, (SA* )&senderAddr, &addrLen);
			if (length == -1) { 
				printFailed();								
			}
			char* ipr = inet_ntoa(senderAddr.sin_addr);			
			debug("Got rt packet from %s, length = %d", ipr, length);									
			processRtResponse(buf, length, senderAddr, rtSocket);			
		}
		// if received a ping
		if (FD_ISSET(pgSocket, &set)){
			bzero(buf, MAXLINE);
			bzero(&senderAddr, addrLen);
		 	addrLen = sizeof(senderAddr);
			int length = recvfrom(pgSocket, buf, MAXLINE, 0, (SA* )&senderAddr, &addrLen);
			if (length == -1) { 
				printFailed();								
			}

			processPgResponse(buf, length, senderAddr, addrLen);
		}

		if (mcastRecvSd > 0 && FD_ISSET(mcastRecvSd, &set)){
			bzero(buf, MAXLINE);
			bzero(&senderAddr, addrLen);
		 	addrLen = sizeof(senderAddr);
			int length = recvfrom(mcastRecvSd, buf, MAXLINE, 0, (SA* )&senderAddr, &addrLen);
			if (length == -1) { 
				printFailed();								
			}
			processMulticastRecv(buf, length, senderAddr, addrLen);

		}	
	}
	free(buf);
}
开发者ID:myroman,项目名称:beta,代码行数:78,代码来源:tour.c


示例14: main

int main(int argc,char *argv[])
{
    if(argc<3)
    {
        printf("Enter servername and portno.\nUsage:\n./bob <serveraddr here localhost> <portno. say 5000>");
    }
    int portno=atoi(argv[2]);
    struct sockaddr_in serv_addr;
    struct hostent *server;
    server=gethostbyname(argv[1]);
    if(server==NULL)
    {
        printf("Unable to locate server");
        exit(0);
    }
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        printf("Socket not created");
        exit(0);
    }
    bzero((char *)&serv_addr,sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(portno);
    bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);
    char buf[200];
    if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
    {
        printf("Unable to connect");
        exit(0);
    }
    while(1)
    {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(STDIN,&readfds);
        FD_SET(sockfd,&readfds);
        select(sockfd+1,&readfds,NULL,NULL,NULL);
        if(FD_ISSET(STDIN,&readfds))
        {
            gets(buf);
            int n=write(sockfd,buf,strlen(buf));
            if(n<0)
            {
                printf("\nUnable to send text to client\n");
                exit(0);
            }
            if(strcmp(buf,"EXIT")==0)
            {
                exit(0);
            }

        }
        if(FD_ISSET(sockfd,&readfds))
        {
            bzero(buf,sizeof(buf));
            int n=read(sockfd,buf,199);
            if(n<0)
            {
                printf("Unable to read");
                exit(0);
            }
            printf("[server]>>%s\n",buf);

        }

    }
            return 0;
}
开发者ID:drake01,项目名称:torprojectgsoc2012,代码行数:69,代码来源:bob.c


示例15: main

int main(int argc, char *argv[])
{
	int listen_fd, fd;
	int yes = 1;
	int addrlen;
	struct sockaddr_in addr;
	fd_set master_fds, read_fds;

	printf("Server: init\n");

	/* get new socket & allow immediately reusing reserved port */
	listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

	/* server port and address */
	bzero(&addr, sizeof(addr));	
	addr.sin_family = AF_INET;	/* host byte order */
	addr.sin_port = htons(SERVER_PORT);	/* short, network byte order */
	addr.sin_addr.s_addr = INADDR_ANY;	/* host ip */

	if (bind(listen_fd, (struct sockaddr*)&addr, sizeof(struct sockaddr))
								 == -1 ) {
		perror("Server: bind");
		exit(1);
	}

	if (listen(listen_fd, BACKLOG) == -1 ) {
		perror("Server: listen");
		exit(1);
	}

	/* keep record of connections */
	FD_ZERO(&master_fds);
	FD_SET(listen_fd, &master_fds);

	/* main loop */
	while (1) {

		/* select modifies read_fds */
		read_fds = master_fds;
		if (select(MAXFD+1, &read_fds, NULL, NULL, NULL) == -1) {
			perror("Server: select");
			continue;
		}

		/* iterate read_fds for new data/connection */
		for (fd = 0; fd <= MAXFD; fd++) {
			if (FD_ISSET(fd, &read_fds)) {
				if (fd == listen_fd) {
					/* create and store to master */
					new_connection(fd, &master_fds);
				} else {
					/* handle and delete from master */ 
					handle_connection(fd, &master_fds);
				}
			}
		}
	}

	/* should never get here */
	close(listen_fd);
}
开发者ID:surfmikko,项目名称:wstools,代码行数:62,代码来源:server.c


示例16: Curl_socket_check


//.........这里部分代码省略.........
  ret = 0;
  num = 0;
  if(readfd0 != CURL_SOCKET_BAD) {
    if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
      ret |= CURL_CSELECT_IN;
    if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
      ret |= CURL_CSELECT_ERR;
    num++;
  }
  if(readfd1 != CURL_SOCKET_BAD) {
    if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
      ret |= CURL_CSELECT_IN2;
    if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
      ret |= CURL_CSELECT_ERR;
    num++;
  }
  if(writefd != CURL_SOCKET_BAD) {
    if(pfd[num].revents & (POLLWRNORM|POLLOUT))
      ret |= CURL_CSELECT_OUT;
    if(pfd[num].revents & (POLLERR|POLLHUP|POLLNVAL))
      ret |= CURL_CSELECT_ERR;
  }

  return ret;

#else  /* HAVE_POLL_FINE */

  FD_ZERO(&fds_err);
  maxfd = (curl_socket_t)-1;

  FD_ZERO(&fds_read);
  if(readfd0 != CURL_SOCKET_BAD) {
    VERIFY_SOCK(readfd0);
    FD_SET(readfd0, &fds_read);
    FD_SET(readfd0, &fds_err);
    maxfd = readfd0;
  }
  if(readfd1 != CURL_SOCKET_BAD) {
    VERIFY_SOCK(readfd1);
    FD_SET(readfd1, &fds_read);
    FD_SET(readfd1, &fds_err);
    if(readfd1 > maxfd)
      maxfd = readfd1;
  }

  FD_ZERO(&fds_write);
  if(writefd != CURL_SOCKET_BAD) {
    VERIFY_SOCK(writefd);
    FD_SET(writefd, &fds_write);
    FD_SET(writefd, &fds_err);
    if(writefd > maxfd)
      maxfd = writefd;
  }

  ptimeout = (timeout_ms < 0) ? NULL : &pending_tv;

  do {
    if(timeout_ms > 0) {
      pending_tv.tv_sec = pending_ms / 1000;
      pending_tv.tv_usec = (pending_ms % 1000) * 1000;
    }
    else if(!timeout_ms) {
      pending_tv.tv_sec = 0;
      pending_tv.tv_usec = 0;
    }
开发者ID:Andy-hpliu,项目名称:curl,代码行数:66,代码来源:select.c


示例17: main


//.........这里部分代码省略.........
// set socket options for IP multicast
// should be ignored for unicast traffic
    if (setsockopt(sock_out, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loopch, sizeof(loopch)) < 0) {
        fprintf(stderr,"Error: could not set IP_MULTICAST_LOOP socket options! Exiting!\n");
        exit(-1);
    }; // end if



    int fd = pcap_get_selectable_fd(pcaphandle);

    if (fd < 0) {
        fprintf(stderr,"Error: could not get file description for select\n");
        exit(-1);
    }; // end if


    timeouts=0;
    packetsequence=0;

// endless loop
    while (forever) {

        // blocking read with timeout: so we use a select
        fd_set rfds;
        struct timeval tv;


        // set timeout to 1 second
        tv.tv_sec = 1;
        tv.tv_usec = 0;

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

        ret= select(fd+1,&rfds,NULL,NULL,&tv);

        if (ret < 0) {
            fprintf(stderr,"Error: select fails (errno=%d)\n",errno);
            exit(-1);
        }; // end if

        // ret=0, we hit a timeout
        if (ret == 0) {
            timeouts++;

            // we stop if we have not received any data during 10 minutes
            if (timeouts > 600) {
                break;
            }; // end if

//fprintf(stderr,"timeout! \n");
            continue;
        }; // end if

        // reset timeouts
        timeouts=0;
        // we have received data, let's check if it is something we can use
        ret = pcap_next_ex( pcaphandle, &header, &packet);

        if (ret == -1) {
            fprintf(stderr,"Error: pcap_next_ex returns an error: %s\n",pcap_geterr(pcaphandle));
            exit(-1);
        }; // end if

        len=header->len;
开发者ID:EQ4,项目名称:DSTK,代码行数:67,代码来源:cap2rpc.c


示例18: Curl_poll


//.........这里部分代码省略.........
  } while(r == -1);

  if(r < 0)
    return -1;
  if(r == 0)
    return 0;

  for(i = 0; i < nfds; i++) {
    if(ufds[i].fd == CURL_SOCKET_BAD)
      continue;
    if(ufds[i].revents & POLLHUP)
      ufds[i].revents |= POLLIN;
    if(ufds[i].revents & POLLERR)
      ufds[ 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ FD_TO_SOCKET函数代码示例发布时间:2022-05-30
下一篇:
C++ FD_ISSET函数代码示例发布时间: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