您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ tcp_close函数代码示例

51自学网 2021-06-03 08:42:09
  C++
这篇教程C++ tcp_close函数代码示例写得很实用,希望能帮到您。

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

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

示例1: main

int main(void){    int sd = -1;    gnutls_global_init();    try    {        /* Allow connections to servers that have OpenPGP keys as well.         */        gnutls::client_session session;        /* X509 stuff */        gnutls::certificate_credentials credentials;        /* sets the trusted cas file         */        credentials.set_x509_trust_file(CAFILE, GNUTLS_X509_FMT_PEM);        /* put the x509 credentials to the current session         */        session.set_credentials(credentials);        /* Use default priorities */        session.set_priority ("NORMAL", NULL);        /* connect to the peer         */        sd = tcp_connect();        session.set_transport_ptr((gnutls_transport_ptr_t) sd);        /* Perform the TLS handshake         */        int ret = session.handshake();        if (ret < 0)        {            throw std::runtime_error("Handshake failed");        }        else        {            std::cout << "- Handshake was completed" << std::endl;        }        session.send(MSG, strlen(MSG));        char buffer[MAX_BUF + 1];        ret = session.recv(buffer, MAX_BUF);        if (ret == 0)        {            throw std::runtime_error("Peer has closed the TLS connection");        }        else if (ret < 0)        {            throw std::runtime_error(gnutls_strerror(ret));        }        std::cout << "- Received " << ret << " bytes:" << std::endl;        std::cout.write(buffer, ret);        std::cout << std::endl;        session.bye(GNUTLS_SHUT_RDWR);    }    catch (std::exception &ex)    {        std::cerr << "Exception caught: " << ex.what() << std::endl;    }    if (sd != -1)        tcp_close(sd);    gnutls_global_deinit();    return 0;}
开发者ID:ares89,项目名称:vlc,代码行数:73,


示例2: tcp_input

//.........这里部分代码省略.........		  }		}		if (so->so_state & SS_CTL) {		    goto cont_input;		}	    }	    /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */	  }	  if (so->so_emu & EMU_NOCONNECT) {	    so->so_emu &= ~EMU_NOCONNECT;	    goto cont_input;	  }	  if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {	    u_char code=ICMP_UNREACH_NET;	    DEBUG_MISC((dfd," tcp fconnect errno = %d-%s/n",			errno,strerror(errno)));	    if(errno == ECONNREFUSED) {	      /* ACK the SYN, send RST to refuse the connection */	      tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,			  TH_RST|TH_ACK);	    } else {	      if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;	      HTONL(ti->ti_seq);             /* restore tcp header */	      HTONL(ti->ti_ack);	      HTONS(ti->ti_win);	      HTONS(ti->ti_urp);	      m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);	      m->m_len  += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);	      *ip=save_ip;	      icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));	    }            tcp_close(tp);	    m_free(m);	  } else {	    /*	     * Haven't connected yet, save the current mbuf	     * and ti, and return	     * XXX Some OS's don't tell us whether the connect()	     * succeeded or not.  So we must time it out.	     */	    so->so_m = m;	    so->so_ti = ti;	    tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;	    tp->t_state = TCPS_SYN_RECEIVED;	  }	  return;	cont_conn:	  /* m==NULL	   * Check if the connect succeeded	   */	  if (so->so_state & SS_NOFDREF) {	    tp = tcp_close(tp);	    goto dropwithreset;	  }	cont_input:	  tcp_template(tp);	  if (optp)	    tcp_dooptions(tp, (u_char *)optp, optlen, ti);	  if (iss)	    tp->iss = iss;	  else
开发者ID:16aug,项目名称:nvmeqemu,代码行数:67,


示例3: tcp_timer_2msl

voidtcp_timer_2msl(void *xtp){	struct tcpcb *tp = xtp;	struct inpcb *inp;	CURVNET_SET(tp->t_vnet);#ifdef TCPDEBUG	int ostate;	ostate = tp->t_state;#endif	/*	 * XXXRW: Does this actually happen?	 */	INP_INFO_WLOCK(&V_tcbinfo);	inp = tp->t_inpcb;	/*	 * XXXRW: While this assert is in fact correct, bugs in the tcpcb	 * tear-down mean we need it as a work-around for races between	 * timers and tcp_discardcb().	 *	 * KASSERT(inp != NULL, ("tcp_timer_2msl: inp == NULL"));	 */	if (inp == NULL) {		tcp_timer_race++;		INP_INFO_WUNLOCK(&V_tcbinfo);		CURVNET_RESTORE();		return;	}	INP_WLOCK(inp);	tcp_free_sackholes(tp);	if ((inp->inp_flags & INP_DROPPED) || callout_pending(&tp->t_timers->tt_2msl) ||	    !callout_active(&tp->t_timers->tt_2msl)) {		INP_WUNLOCK(tp->t_inpcb);		INP_INFO_WUNLOCK(&V_tcbinfo);		CURVNET_RESTORE();		return;	}	callout_deactivate(&tp->t_timers->tt_2msl);	/*	 * 2 MSL timeout in shutdown went off.  If we're closed but	 * still waiting for peer to close and connection has been idle	 * too long, or if 2MSL time is up from TIME_WAIT, delete connection	 * control block.  Otherwise, check again in a bit.	 *	 * If fastrecycle of FIN_WAIT_2, in FIN_WAIT_2 and receiver has closed, 	 * there's no point in hanging onto FIN_WAIT_2 socket. Just close it. 	 * Ignore fact that there were recent incoming segments.	 */	if (tcp_fast_finwait2_recycle && tp->t_state == TCPS_FIN_WAIT_2 &&	    tp->t_inpcb && tp->t_inpcb->inp_socket && 	    (tp->t_inpcb->inp_socket->so_rcv.sb_state & SBS_CANTRCVMORE)) {		TCPSTAT_INC(tcps_finwait2_drops);		tp = tcp_close(tp);             	} else {		if (tp->t_state != TCPS_TIME_WAIT &&		   ticks - tp->t_rcvtime <= TP_MAXIDLE(tp))		       callout_reset_on(&tp->t_timers->tt_2msl,			   TP_KEEPINTVL(tp), tcp_timer_2msl, tp, INP_CPU(inp));	       else		       tp = tcp_close(tp);       }#ifdef TCPDEBUG	if (tp != NULL && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))		tcp_trace(TA_USER, ostate, tp, (void *)0, (struct tcphdr *)0,			  PRU_SLOWTIMO);#endif	if (tp != NULL)		INP_WUNLOCK(inp);	INP_INFO_WUNLOCK(&V_tcbinfo);	CURVNET_RESTORE();}
开发者ID:carriercomm,项目名称:libuinet,代码行数:73,


示例4: http_tcpapp

void http_tcpapp(unsigned int idx, char *rx, unsigned int rx_len, unsigned char *tx){  unsigned int tx_len;  DEBUGOUT("HTTP: TCP app/n");  switch(http_table[idx].status)  {    case HTTP_CLOSED: //new connection      if(rx_len)      {        if(strncmpi(rx, "GET", 3) == 0)        {          rx     += 3+1;          rx_len -= 3+1;          http_sendfile(idx, rx, tx);        }        else if(strncmpi(rx, "POST", 4) == 0)        {          rx     += 4+1;          rx_len -= 4+1;          if(strncmpi(rx, "/station", 8) == 0)          {            http_table[idx].status = HTTP_STATION;            rx = (char*)http_skiphd(rx, &rx_len);          }          else if(strncmpi(rx, "/alarm", 6) == 0)          {            http_table[idx].status = HTTP_ALARM;            rx = http_skiphd(rx, &rx_len);          }          else if(strncmpi(rx, "/settings", 9) == 0)          {            http_table[idx].status = HTTP_SETTINGS;            rx = http_skiphd(rx, &rx_len);          }          else          {            http_sendfile(idx, rx, tx);          }        }        else        {          tx_len = sprintf((char*)tx, HTTP_400_HEADER"Error 400 Bad request/r/n/r/n");          tcp_send(idx, tx_len, 0);          tcp_close(idx);        }      }      break;    case HTTP_SEND:      http_sendfile(idx, 0, tx);      break;  }  //parse station, alarm or settings  switch(http_table[idx].status)  {    case HTTP_STATION:      if(rx_len)      {        http_station(rx, rx_len);        http_sendfile(idx, "/station", tx);      }      else      {        tcp_send(idx, 0, 0);      }      break;    case HTTP_ALARM:      if(rx_len)      {        http_alarm(rx, rx_len);        http_sendfile(idx, "/alarm", tx);      }      else      {        tcp_send(idx, 0, 0);      }      break;    case HTTP_SETTINGS:      if(rx_len)      {        http_settings(rx, rx_len);        http_sendfile(idx, "/settings", tx);      }      else      {        tcp_send(idx, 0, 0);      }      break;  }  return;}
开发者ID:Bob4ik888,项目名称:WebRadio,代码行数:97,


示例5: tcp_slowtmr

/** * Called every 500 ms and implements the retransmission timer and the timer that * removes PCBs that have been in TIME-WAIT for enough time. It also increments * various timers such as the inactivity timer in each PCB. * * Automatically called from tcp_tmr(). */void tcp_slowtmr(void){    TCP_PCB *pcb, *pcb2, *prev;    uint16 eff_wnd;    uint8 err= ERR_OK;    ++tcp_ticks;    /* Steps through all of the active PCBs. */    prev = NULL;    pcb = &stTcpPcb;    if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX)    {        printf("SYN SENT CLOSED/n");        pcb->state = CLOSED;        tcp_pcb_purge(pcb);	    tcp_close(pcb);        return;    }    else if (pcb->nrtx == TCP_MAXRTX)    {        printf("TCP MAXRTX CLOSED/n");        pcb->state = CLOSED;        tcp_pcb_purge(pcb);	    tcp_close(pcb);        return;    }    else    {        if (pcb->persist_backoff > 0)        {            /* If snd_wnd is zero, use persist timer to send 1 byte probes             * instead of using the standard retransmission mechanism. */            pcb->persist_cnt++;            if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1])            {                pcb->persist_cnt = 0;                if (pcb->persist_backoff < sizeof(tcp_persist_backoff))                {                    pcb->persist_backoff++;                }                tcp_zero_window_probe(pcb);            }        }        else        {            /* Increase the retransmission timer if it is running */            if (pcb->rtime >= 0)                ++pcb->rtime;            if (pcb->unacked != NULL && pcb->rtime >= pcb->rto)            {                /* Double retransmission time-out unless we are trying to                 * connect to somebody (i.e., we are in SYN_SENT). */                if (pcb->state != SYN_SENT)                {                    pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];                }                /* Reset the retransmission timer. */                pcb->rtime = 0;                /* Reduce congestion window and ssthresh. */                eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);                pcb->ssthresh = eff_wnd >> 1;                if (pcb->ssthresh < pcb->mss)                {                    pcb->ssthresh = pcb->mss * 2;                }                pcb->cwnd = pcb->mss;                /* The following needs to be called AFTER cwnd is set to one                   mss - STJ */                tcp_rexmit_rto(pcb);            }        }    }
开发者ID:imaginegit,项目名称:wifisdk,代码行数:85,


示例6: tcp_cleanup

void tcp_cleanup(Slirp *slirp){    while (slirp->tcb.so_next != &slirp->tcb) {        tcp_close(sototcpcb(slirp->tcb.so_next));    }}
开发者ID:8tab,项目名称:qemu,代码行数:6,


示例7: client_test

void client_test(void* args){#ifdef _WIN32    WSADATA wsd;    WSAStartup(0x0002, &wsd);#endif    SOCKET_T sockfd = 0;    int      argc = 0;    char**   argv = 0;    set_args(argc, argv, *static_cast<func_args*>(args));    tcp_connect(sockfd);#ifdef NON_BLOCKING    tcp_set_nonblocking(sockfd);#endif    SSL_METHOD* method = TLSv1_client_method();    SSL_CTX*    ctx = SSL_CTX_new(method);    set_certs(ctx);    SSL* ssl = SSL_new(ctx);    SSL_set_fd(ssl, sockfd);#ifdef NON_BLOCKING    NonBlockingSSL_Connect(ssl, ctx, sockfd);#else    // if you get an error here see note at top of README    if (SSL_connect(ssl) != SSL_SUCCESS)           ClientError(ctx, ssl, sockfd, "SSL_connect failed");#endif    showPeer(ssl);    const char* cipher = 0;    int index = 0;    char list[1024];    strncpy(list, "cipherlist", 11);    while ( (cipher = SSL_get_cipher_list(ssl, index++)) ) {        strncat(list, ":", 2);        strncat(list, cipher, strlen(cipher) + 1);    }    printf("%s/n", list);    printf("Using Cipher Suite: %s/n", SSL_get_cipher(ssl));    char msg[] = "hello yassl!";    if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg))        ClientError(ctx, ssl, sockfd, "SSL_write failed");    char reply[1024];    int input = SSL_read(ssl, reply, sizeof(reply));    if (input > 0) {        reply[input] = 0;        printf("Server response: %s/n", reply);    }#ifdef TEST_RESUME    SSL_SESSION* session   = SSL_get_session(ssl);    SSL*         sslResume = SSL_new(ctx);#endif    SSL_shutdown(ssl);    SSL_free(ssl);    tcp_close(sockfd);#ifdef TEST_RESUME    tcp_connect(sockfd);    SSL_set_fd(sslResume, sockfd);    SSL_set_session(sslResume, session);    if (SSL_connect(sslResume) != SSL_SUCCESS)        ClientError(ctx, sslResume, sockfd, "SSL_resume failed");    showPeer(sslResume);    if (SSL_write(sslResume, msg, sizeof(msg)) != sizeof(msg))        ClientError(ctx, sslResume, sockfd, "SSL_write failed");    input = SSL_read(sslResume, reply, sizeof(reply));    if (input > 0) {        reply[input] = 0;        printf("Server response: %s/n", reply);    }    SSL_shutdown(sslResume);    SSL_free(sslResume);    tcp_close(sockfd);#endif // TEST_RESUME    SSL_CTX_free(ctx);    ((func_args*)args)->return_code = 0;}
开发者ID:flyingtime,项目名称:boxee,代码行数:92,


示例8: rtsp_connect

int rtsp_connect(struct rtsp_client * rtsp, const char * host,		unsigned int port, const char * mrl){	struct tcp_pcb * tp;	in_addr_t host_addr;	if (!inet_aton(host, (struct in_addr *)&host_addr)) {		return -1;	}	if ((tp = tcp_alloc()) == NULL) {		ERR("can't allocate socket!");		return -1;	}	if (port == 0) {		port = rtsp->port;		if (port == 0)			port = 554;	}	INF("RTSP://%s:%d/%s", host, port, mrl);	if (tcp_connect(tp, host_addr, htons(port)) < 0) {		ERR("can't connect to host!");		tcp_close(tp);		return -1;	}	rtsp->tcp = tp;	rtsp->port = port;	rtsp->host_addr = host_addr;	rtsp->rtp.faddr = host_addr;	rtsp->cseq = 1;	strcpy(rtsp->host_name, host);	strcpy(rtsp->media_name, mrl);	if (rtsp_request_options(rtsp) < 0) {		ERR("rtsp_request_options() failed!");		return -1;	}	if (rtsp_request_describe(rtsp) < 0) {		ERR("rtsp_request_describe() failed!");		return -1;	}	if (rtsp_sdp_decode(rtsp) < 0) {		ERR("rtsp_sdp_decode() failed!");		return -1;	}	INF("Track:/"%s/"", rtsp->track_name);	if (rtsp_request_setup(rtsp) < 0) {		ERR("rtsp_request_setup() failed!");		return -1;	}	if (rtsp_request_play(rtsp) < 0) {		ERR("rtsp_request_play() failed!");		return -1;	}	return 0;}
开发者ID:bobmittmann,项目名称:thinkos,代码行数:67,


示例9: rtsp_line_recv

int rtsp_line_recv(struct rtsp_client * rtsp, char * line,		unsigned int len){	struct tcp_pcb * tp = rtsp->tcp;	int rem;	int cnt;	int pos;	int lin;	int c1;	int c2;	int n;	cnt = rtsp->cnt;	pos = rtsp->pos;	lin = rtsp->lin;	c1 = (pos) ? rtsp->buf[pos - 1] : '/0';	/* receive SDP payload */	for (;;) {		/* search for end of line */		while (pos < cnt) {			c2 = rtsp->buf[pos++];			if (c1 == '/r' && c2 == '/n') {				char * dst = line;				char * src = &rtsp->buf[lin];				int i;				n = pos - lin - 2;				if (n > len)					n = len;				for (i = 0; i < n; ++i)					dst[i] = src[i];				/* move to the next line */				lin = pos;				rtsp->lin = lin;				rtsp->pos = lin;				return n;			}			c1 = c2;		}		/* */		if (rtsp->resp.content_len == rtsp->resp.content_pos) {			/* get the number of remaining characters, ignoring			 * a possible CR at the end*/			n = pos - lin - (c1 == '/r') ? 1 : 0;			if (n != 0) {				/* this is the last line and there is no CR+LF at the end of it */				char * dst = line;				char * src = &rtsp->buf[lin];				int i;				if (n > len)					n = len;				for (i = 0; i < n; ++i)					dst[i] = src[i];			}			/* update our pointers */			rtsp->pos = pos;			rtsp->lin = lin;			return n;		}		if (RTSP_CLIENT_BUF_LEN == cnt) {			int i;			int j;			if (lin == 0) {				ERR("buffer overflow!");				return -1;			}			/* move remaining data to the beginning of the buffer */			n = cnt - lin;			for (i = 0, j = lin; i < n; ++i, ++j)				rtsp->buf[i] = rtsp->buf[j];			cnt = n;			pos = n;			lin = 0;		}		/* free space in the input buffer */		rem = RTSP_CLIENT_BUF_LEN - cnt;		/* read more data */		if ((n = tcp_recv(tp, &rtsp->buf[cnt], rem)) <= 0) {			tcp_close(tp);			return n;		}		rtsp->resp.content_pos += n;		cnt += n;		rtsp->cnt = cnt;	}	return 0;}
开发者ID:bobmittmann,项目名称:thinkos,代码行数:100,


示例10: main

int main(void) {        char server_buf[BUF_SIZE], client_buf[BUF_SIZE];    char *eth, *ip1, *ip2;    int pid, status, total, read;    int j, v;    ipaddr_t saddr;    eth = getenv("ETH");    if (!eth) {        fprintf(stderr, "The ETH environment variable must be set!/n");        return 1;    }    ip1 = getenv("IP1");    ip2 = getenv("IP2");    if ((!ip1)||(!ip2)) {        fprintf(stderr, "The IP1 and IP2 environment variables must be set!/n");        return 1;    }                /* fill buffer with ASCII pattern 012345670123... */        for (v=0;v<BUF_SIZE;v++) {            client_buf[v] = (v % 8) + 48;        }        /* Client process running in $IP1 */        eth[0] = '1';         if (tcp_socket() != 0) {            fprintf(stderr, "Client: Opening socket failed/n");            return 1;        }                signal(SIGALRM, alarm_handler);        alarm(10);                if (tcp_connect(inet_aton(ip2), 80) != 0) {            fprintf(stderr, "Client: Connecting to server failed/n");            return 1;        }                j = tcp_write(client_buf, BUF_SIZE);        if (j < 1) {            fprintf(stderr, "Client: Writing failed/n");             return 1;        }        fprintf(stderr,"Client: Sent %d Kbytes/n",j);                           if (tcp_close() != 0) {            fprintf(stderr, "Client: Closing connection failed/n");            return 1;        }        signal(SIGALRM, alarm_handler);        alarm(3);        while (tcp_read(client_buf, 4) > 0) {}        alarm(0);        return 0;    }
开发者ID:TrainingProject,项目名称:tcp,代码行数:68,


示例11: rtsp_wait_reply

//.........这里部分代码省略.........	rem = RTSP_CLIENT_BUF_LEN; /* free space in the input buffer */	cnt = 0; /* used space in the input buffer */	ln = 0; /* line start */	pos = 0; /* header position */	c1 = '/0';	/* receive and decode RTSP headers */	while ((n = tcp_recv(tp, &buf[cnt], rem)) > 0)  {		rem -= n;		i = cnt;		cnt += n;		for (; i < cnt; ++i) {			c2 = buf[i];			if (c1 == '/r' && c2 == '/n') {				char * val;				unsigned int hdr;				buf[i - 1] = '/0';#if 0				printf("%s/n", &buf[ln]);#endif				if (i == ln + 1) {					DBG("end of RTSP header");					i++;					rtsp->cnt = cnt;					rtsp->pos = i;					rtsp->lin = i;					if (rtsp->resp.code != 200) {						WARN("Server response code: %d", rtsp->resp.code);						return -1;					}					return 0;				}				if ((hdr = rtsp_parse_hdr(&buf[ln], &val)) == 0) {					WARN("invalid header field: /"%s/"", &buf[ln]);//					return -1;				} else {//					DBG("header field received: %s", rtsp_hdr_name[hdr]);					if (pos == 0) {						if (hdr != HDR_RTSP_1_0) {							WARN("invalid response");							return -1;						}						rtsp->resp.code = atoi(val);					} else {						switch (hdr) {						case HDR_CSEQ:							if (atoi(val) != rtsp->cseq) {								WARN("invalid CSeq");								return -1;							}							break;						case HDR_SESSION:							rtsp->sid = strtoull(val, NULL, 16);							break;						case HDR_TRANSPORT:							rtsp_decode_transport(rtsp, val);							break;						case HDR_CONTENT_LENGTH:							rtsp->resp.content_len = strtoul(val, NULL, 10);//							DBG("Content Length: %d", rtsp->content_len);							break;						}					}				}				/* increment header counter */				pos++;				/* move to the next line */				ln = i + 1;			}			c1 = c2;		}		if (ln != 0) {			int j;			for (i = 0, j = ln; j < cnt; ++i, ++j)				buf[i] = buf[j];			cnt = i;			rem = RTSP_CLIENT_BUF_LEN - i;			ln = 0;		}		if (rem <= 0) {			ERR("buffer ovreflow!");			return -1;		}	}	tcp_close(tp);	return -1;}
开发者ID:bobmittmann,项目名称:thinkos,代码行数:101,


示例12: lwip_socket_ioctl

STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {    lwip_socket_obj_t *socket = self_in;    mp_uint_t ret;    if (request == MP_STREAM_POLL) {        uintptr_t flags = arg;        ret = 0;        if (flags & MP_STREAM_POLL_RD && socket->incoming.pbuf != NULL) {            ret |= MP_STREAM_POLL_RD;        }        // Note: pcb.tcp==NULL if state<0, and in this case we can't call tcp_sndbuf        if (flags & MP_STREAM_POLL_WR && socket->pcb.tcp != NULL && tcp_sndbuf(socket->pcb.tcp) > 0) {            ret |= MP_STREAM_POLL_WR;        }        if (socket->state == STATE_NEW) {            // New sockets are not connected so set HUP            ret |= flags & MP_STREAM_POLL_HUP;        } else if (socket->state == STATE_PEER_CLOSED) {            // Peer-closed socket is both readable and writable: read will            // return EOF, write - error. Without this poll will hang on a            // socket which was closed by peer.            ret |= flags & (MP_STREAM_POLL_RD | MP_STREAM_POLL_WR);        } else if (socket->state == ERR_RST) {            // Socket was reset by peer, a write will return an error            ret |= flags & (MP_STREAM_POLL_WR | MP_STREAM_POLL_HUP);        } else if (socket->state < 0) {            // Socket in some other error state, use catch-all ERR flag            // TODO: may need to set other return flags here            ret |= flags & MP_STREAM_POLL_ERR;        }    } else if (request == MP_STREAM_CLOSE) {        bool socket_is_listener = false;        if (socket->pcb.tcp == NULL) {            return 0;        }        switch (socket->type) {            case MOD_NETWORK_SOCK_STREAM: {                if (socket->pcb.tcp->state == LISTEN) {                    socket_is_listener = true;                }                if (tcp_close(socket->pcb.tcp) != ERR_OK) {                    DEBUG_printf("lwip_close: had to call tcp_abort()/n");                    tcp_abort(socket->pcb.tcp);                }                break;            }            case MOD_NETWORK_SOCK_DGRAM: udp_remove(socket->pcb.udp); break;            //case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break;        }        socket->pcb.tcp = NULL;        socket->state = _ERR_BADF;        if (socket->incoming.pbuf != NULL) {            if (!socket_is_listener) {                pbuf_free(socket->incoming.pbuf);            } else {                tcp_abort(socket->incoming.connection);            }            socket->incoming.pbuf = NULL;        }        ret = 0;    } else {        *errcode = MP_EINVAL;        ret = MP_STREAM_ERROR;    }    return ret;}
开发者ID:learnforpractice,项目名称:micropython,代码行数:73,


示例13: vmdirConnAccept

//.........这里部分代码省略.........            errno = WSAGetLastError();#endif            VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: select() (port %d) call failed: %d.", __func__, dwPort, errno);            VmDirSleep( 1000 );            continue;        } else if (retVal == 0)        {            //VMDIR_LOG_INFO( LDAP_DEBUG_CONNS, "%s: select() timeout (port %d)", __func__, dwPort);            continue;        }        if (ip4_fd >= 0 && FD_ISSET(ip4_fd, &poll_fd_set))        {            newsockfd = accept(ip4_fd, (struct sockaddr *) NULL, NULL);        } else if (ip6_fd >= 0 && FD_ISSET(ip6_fd, &poll_fd_set))        {            newsockfd = accept(ip6_fd, (struct sockaddr *) NULL, NULL);        } else        {            VMDIR_LOG_INFO( LDAP_DEBUG_CONNS, "%s: select() returned with no data (port %d), return: %d",                            __func__, dwPort, retVal);            continue;        }        if (newsockfd < 0)        {#ifdef _WIN32            errno = WSAGetLastError();#endif            if (errno != EAGAIN && errno != EWOULDBLOCK )            {                VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: accept() (port %d) failed with errno: %d.",                                 __func__, dwPort, errno );            }            continue;        }        if ( _VmDirFlowCtrlThrEnter() == TRUE )        {            tcp_close(newsockfd);            newsockfd = -1;            VMDIR_LOG_WARNING( VMDIR_LOG_MASK_ALL, "Maxmimum number of concurrent LDAP threads reached. Blocking new connection" );            continue;        }        retVal = VmDirAllocateMemory(                sizeof(VDIR_CONNECTION_CTX),                (PVOID*)&pConnCtx);        BAIL_ON_VMDIR_ERROR(retVal);        pConnCtx->sockFd  = newsockfd;        newsockfd = -1;        pConnCtx->pSockbuf_IO = pSockbuf_IO;        retVal = VmDirCreateThread(&threadId, TRUE, ProcessAConnection, (PVOID)pConnCtx);        if (retVal != 0)        {            VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: VmDirCreateThread() (port) failed with errno: %d",                             __func__, dwPort, errno );            tcp_close(pConnCtx->sockFd);            _VmDirFlowCtrlThrExit();            VMDIR_SAFE_FREE_MEMORY(pConnCtx);            continue;        }        else        {            pConnCtx = NULL; //thread take ownership on pConnCtx            VmDirFreeVmDirThread(&threadId);        }    }cleanup:    VMDIR_UNLOCK_MUTEX(bInLock, gVmdirGlobals.replCycleDoneMutex);    if (ip4_fd >= 0)    {        tcp_close(ip4_fd);    }    if (ip6_fd >= 0)    {        tcp_close(ip6_fd);    }    if (newsockfd >= 0)    {        tcp_close(newsockfd);    }#ifndef _WIN32    raise(SIGTERM);#endif    VMDIR_LOG_INFO( VMDIR_LOG_MASK_ALL, "%s: Connection accept thread: stop (port %d)", __func__, dwPort);    return retVal;error:    goto cleanup;}
开发者ID:divyamehta,项目名称:lightwave,代码行数:101,


示例14: BindListenOnPort

//.........这里部分代码省略.........                                   __func__, errno, reTries);      VmDirSleep(1000);      retValBind = bind(*pSockfd, (struct sockaddr *) pServ_addr, addr_size);   }#endif   if (retValBind != 0)   {      retVal = LDAP_OPERATIONS_ERROR;      //need to free socket ...      BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, pszLocalErrMsg,                      "%s: bind() call failed with errno: %d", __func__, errno );   }   if (listen(*pSockfd, LDAP_PORT_LISTEN_BACKLOG) != 0)   {#ifdef _WIN32      errno = WSAGetLastError();#endif      retVal = LDAP_OPERATIONS_ERROR;      BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, pszLocalErrMsg,                      "%s: listen() call failed with errno: %d", __func__, errno );   }cleanup:    VMDIR_SAFE_FREE_MEMORY(pszLocalErrMsg);    return retVal;error:    if (*pSockfd >= 0)    {        tcp_close(*pSockfd);        *pSockfd = -1;    }    VMDIR_LOG_ERROR(VMDIR_LOG_MASK_ALL, VDIR_SAFE_STRING(pszLocalErrMsg));    goto cleanup;}/* *  We own pConnection and delete it when done. */staticDWORDProcessAConnection(   PVOID pArg   ){   VDIR_CONNECTION *pConn = NULL;   int            retVal = LDAP_SUCCESS;   ber_tag_t      tag = LBER_ERROR;   ber_len_t      len = 0;   BerElement *   ber = NULL;   ber_int_t      msgid = -1;   PVDIR_OPERATION pOperation = NULL;   int            reTries = 0;   BOOLEAN                      bDownOpThrCount = FALSE;   PVDIR_CONNECTION_CTX pConnCtx = NULL;   // increment operation thread counter   retVal = VmDirSyncCounterIncrement(gVmdirGlobals.pOperationThrSyncCounter);   BAIL_ON_VMDIR_ERROR(retVal);   bDownOpThrCount = TRUE;   pConnCtx = (PVDIR_CONNECTION_CTX)pArg;
开发者ID:divyamehta,项目名称:lightwave,代码行数:67,


示例15: do_close_internal

/** * Internal helper function to close a TCP netconn: since this sometimes * doesn't work at the first attempt, this function is called from multiple * places. * * @param conn the TCP netconn to close */static voiddo_close_internal(struct netconn *conn){  err_t err;  u8_t shut, shut_rx, shut_tx, close;  LWIP_ASSERT("invalid conn", (conn != NULL));  LWIP_ASSERT("this is for tcp netconns only", (conn->type == NETCONN_TCP));  LWIP_ASSERT("conn must be in state NETCONN_CLOSE", (conn->state == NETCONN_CLOSE));  LWIP_ASSERT("pcb already closed", (conn->pcb.tcp != NULL));  LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL);  shut = conn->current_msg->msg.sd.shut;  shut_rx = shut & NETCONN_SHUT_RD;  shut_tx = shut & NETCONN_SHUT_WR;  /* shutting down both ends is the same as closing */  close = shut == NETCONN_SHUT_RDWR;  /* Set back some callback pointers */  if (close) {    tcp_arg(conn->pcb.tcp, NULL);  }  if (conn->pcb.tcp->state == LISTEN) {    tcp_accept(conn->pcb.tcp, NULL);  } else {    /* some callbacks have to be reset if tcp_close is not successful */    if (shut_rx) {      tcp_recv(conn->pcb.tcp, NULL);      tcp_accept(conn->pcb.tcp, NULL);    }    if (shut_tx) {      tcp_sent(conn->pcb.tcp, NULL);    }    if (close) {      tcp_poll(conn->pcb.tcp, NULL, 4);      tcp_err(conn->pcb.tcp, NULL);    }  }  /* Try to close the connection */  if (shut == NETCONN_SHUT_RDWR) {    err = tcp_close(conn->pcb.tcp);  } else {    err = tcp_shutdown(conn->pcb.tcp, shut & NETCONN_SHUT_RD, shut & NETCONN_SHUT_WR);  }  if (err == ERR_OK) {    /* Closing succeeded */    conn->current_msg->err = ERR_OK;    conn->current_msg = NULL;    conn->state = NETCONN_NONE;    /* Set back some callback pointers as conn is going away */    conn->pcb.tcp = NULL;    /* Trigger select() in socket layer. Make sure everybody notices activity       on the connection, error first! */    if (close) {      API_EVENT(conn, NETCONN_EVT_ERROR, 0);    }    if (shut_rx) {      API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);    }    if (shut_tx) {      API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0);    }    /* wake up the application task */    sys_sem_signal(&conn->op_completed);  } else {    /* Closing failed, restore some of the callbacks */    /* Closing of listen pcb will never fail! */    LWIP_ASSERT("Closing a listen pcb may not fail!", (conn->pcb.tcp->state != LISTEN));    tcp_sent(conn->pcb.tcp, sent_tcp);    tcp_poll(conn->pcb.tcp, poll_tcp, 4);    tcp_err(conn->pcb.tcp, err_tcp);    tcp_arg(conn->pcb.tcp, conn);    /* don't restore recv callback: we don't want to receive any more data */  }  /* If closing didn't succeed, we get called again either     from poll_tcp or from sent_tcp */}
开发者ID:apmorton,项目名称:libxenon,代码行数:84,


示例16: __attribute__

//.........这里部分代码省略.........					case TELOPT_ECHO:						tn_opt_will(tp, &opt, c);						break;					case TELOPT_BINARY:						tn_opt_will(tp, &opt, c);						break;					default:						tn_opt_wont(tp, &opt, c);					}					state = TN_DATA;					break;				case TN_WONT_RCVD:					DCC_LOG1(LOG_TRACE, "WONT %s", TELOPT(c));					tn_opt_dont(tp, &opt, c);					state = TN_DATA;					break;				case TN_WILL_RCVD:					DCC_LOG1(LOG_TRACE, "WILL %s", TELOPT(c));					switch (c) {					case TELOPT_ECHO:						tn_opt_dont(tp, &opt, c);						break;					case TELOPT_SGA:						tn_opt_do(tp, &opt, c);						break;					case TELOPT_BINARY:						tn_opt_do(tp, &opt, c);						binary = 1;						break;					default:						tn_opt_dont(tp, &opt, c);					}					state = TN_DATA;					break;				case TN_SUBOPTION_ID:					state = TN_SUBOPTION;					break;				case TN_SUBOPTION:					if (c == IAC)						state = TN_SB_IAC_RCVD;					if (sb_len < TN_SB_BUF_LEN) {						DCC_LOG1(LOG_TRACE, "suboption: %d", c);					}//					sb_buf[sb_len++] = c;					break;				case TN_SB_IAC_RCVD:					if (c == SE) {						state = TN_DATA;//						tn_suboption(cpc, sb_buf, sb_len);					} else {						state = TN_SUBOPTION;//						sb_buf[sb_len++] = c;					}					break;				case TN_INVALID_SUBOPTION:					if (c == IAC)						state = TN_INVALID_SB_IAC_RCVD;					break;				case TN_INVALID_SB_IAC_RCVD:					if (c == SE)						state = TN_DATA;					else						state = TN_INVALID_SUBOPTION;					break;				default:					DCC_LOG1(LOG_WARNING, "invalid state: %d!!", state);					break;				}			}		}		DCC_LOG(LOG_TRACE, "close...");		tcp_close(tp);		INF("TELNET connection closed.");		tn->tp  = NULL;	}	DCC_LOG(LOG_ERROR, "thread loop break!!!");	for(;;);}
开发者ID:k0059,项目名称:yard-ice,代码行数:101,


示例17: main

int main(int argc, char **argv){	int server;	int efd;	struct epoll_event ev, events[10];	server = tcp_create_listener(7878, 1024, 0);	if (server == TCP_ERR) {		printf("server creation fail/n");		return EXIT_FAILURE;	}	efd = epoll_create(10);	if (efd == -1) {		perror("epoll_create");		exit(EXIT_FAILURE);	}	ev.events = EPOLLIN;	ev.data.fd = server;	epoll_ctl(efd, EPOLL_CTL_ADD, server, &ev);	printf("server listening .../n");	int etfd;	int n;	long ecounter = 0;	while(1) {		etfd = epoll_wait(efd, events, 10, -1);		ecounter++;		if (etfd == -1) {			printf("ecounter:%ld/n", ecounter);			perror("epoll_wait");			exit(EXIT_FAILURE);		}		for (n = 0; n < etfd; ++n) {			if ((events[n].events & EPOLLERR) ||				(events[n].events & EPOLLHUP))				 //&& ((!events[n].events & EPOLLIN)				 //|| (!events[n].events & EPOLLOUT))				{					printf("ecounter:%ld/n", ecounter);					perror("epoll error");					close (events[n].data.fd);					continue;				}			if (events[n].data.fd == server) {				printf("ecounter:%ld/n", ecounter);				char ip[64];				int port;				int tryagain;				int cli = tcp_accept(server, ip, 64, &port, 1,						&tryagain);				if (cli == TCP_ERR) {					printf("tryagain: %d/n", tryagain);					printf("accept(): %s/n", strerror(errno));					continue;				}				//tcp_set_keepalive(cli, 10);				printf("-----> Client: %s:%d/n", ip, port);				ev.events = EPOLLIN;				ev.data.fd = cli;				epoll_ctl(efd, EPOLL_CTL_ADD, cli, &ev);			}			else {				if (events[n].events & EPOLLIN) {					printf("ecounter:%ld/n", ecounter);					printf("%d ready for read/n", events[n].data.fd);					int cli = events[n].data.fd;					int tryagain;					char buf[16];					int isreadonce = 0;					ssize_t nread;					memset(buf, '/0', 16);					nread = tcp_read(cli, buf, 16, &tryagain);					if (nread > 0) {						printf("Read: %zd:%d:%s/n", nread,tryagain, buf);						ev.events = events[n].events;						ev.events |= EPOLLOUT;						ev.data.fd = events[n].data.fd;						int rct = epoll_ctl(efd, EPOLL_CTL_MOD, ev.data.fd, &ev);						if (rct == -1)							perror("r:epoll_ctl_mod");					} else {						if (tryagain) {							printf("completed reading: %zd, tryagain:%d/n",							nread, tryagain);							printf("read(): %s/n", strerror(errno));							break;						} else {							printf("client down: %zd/n", nread);							printf("read(): %s/n", strerror(errno));							tcp_close(cli);							break;						}					}				}//.........这里部分代码省略.........
开发者ID:stoned7,项目名称:kopou,代码行数:101,


示例18: telnet_svc_release

int telnet_svc_release(struct telnet_svc * tn){	return tcp_close(tn->tp);}
开发者ID:k0059,项目名称:yard-ice,代码行数:4,


示例19: main

int main(void) {    char client_buf[1], server_buf[1];    char *eth, *ip1, *ip2;    int pid, status;    unsigned char j, v;    ipaddr_t saddr;    eth = getenv("ETH");    if (!eth) {        fprintf(stderr, "The ETH environment variable must be set!/n");        return 1;    }    ip1 = getenv("IP1");    ip2 = getenv("IP2");    if ((!ip1)||(!ip2)) {        fprintf(stderr, "The IP1 and IP2 environment variables must be set!/n");        return 1;    }    pid = fork();    if (pid == -1) {        fprintf(stderr, "Unable to fork client process/n");        return 1;    }    if (pid == 0) {        /* Client process running in $IP1 */          eth[0] = '1';        /*ip_init();*/        if (tcp_socket() != 0) {            fprintf(stderr, "Client: Opening socket failed/n");            return 1;        }        if (tcp_connect(inet_aton(ip2), 80) != 0) {            fprintf(stderr, "Client: Connecting to server failed/n");            return 1;        }                for (v=0; v<255; v++) {            client_buf[0] = v;            if (tcp_write(client_buf, 1) != 1) {                fprintf(stderr, "Client: Writing ASCII character %u failed (", v);                                return 1;            }            printf("Client: Sent ASCII character %u (", v);                    }        /* send last byte (255)*/        client_buf[0] = v;        if (tcp_write(client_buf, 1) != 1) {            fprintf(stderr, "Client: Writing ASCII character %u failed (", v);                        return 1;        }        printf("Client: Sent ASCII character %u (", v);                                if (tcp_close() != 0) {            fprintf(stderr, "Client: Closing connection failed/n");            return 1;        }        signal(SIGALRM, alarm_handler);        alarm(5);        while (tcp_read(server_buf, 4) > 0) {}        alarm(0);        return 0;    } else {        /* Server process running in $IP2 */        eth[0]='2';        if (tcp_socket() != 0) {            fprintf(stderr, "Server: Opening socket failed/n");            return 1;        }        signal(SIGALRM, alarm_handler);        alarm(5);        if (tcp_listen(80, &saddr) < 0) {//.........这里部分代码省略.........
开发者ID:TrainingProject,项目名称:tcp,代码行数:101,


示例20: HelloWorld_recv

/**  * @brief  Called when a data is received on the telnet connection  * @param  arg :the user argument  * @param  pcb :the tcp_pcb that has received the data  * @param  p   :the packet buffer  * @param  err :the error value linked with the received data  * @retval error value  */static err_t HelloWorld_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err){    struct pbuf *q;    struct name *name = (struct name *)arg;    int done;    char *c;    int i;     /* We perform here any necessary processing on the pbuf */    if (p != NULL)     {                /* We call this function to tell the LwIp that we have processed the data */        /* This lets the stack advertise a larger window, so more data can be received*/        tcp_recved(pcb, p->tot_len);        /* Check the name if NULL, no data passed, return withh illegal argument error */        if(!name)         {            pbuf_free(p);            return ERR_ARG;        }        done = 0;        for(q=p; q != NULL; q = q->next)         {            c = q->payload;            for(i=0; i<q->len && !done; i++)             {                done = ((c[i] == '/r') || (c[i] == '/n'));                if(name->length < MAX_NAME_SIZE)                 {                    name->bytes[name->length++] = c[i];                }            }        }        if(done)         {            if(name->bytes[name->length-2] != '/r' || name->bytes[name->length-1] != '/n')             {                if((name->bytes[name->length-1] == '/r' || name->bytes[name->length-1] == '/n')                     && (name->length+1 <= MAX_NAME_SIZE))                 {                    name->length += 1;                }                 else if(name->length+2 <= MAX_NAME_SIZE)                 {                    name->length += 2;                }                 else                 {                    name->length = MAX_NAME_SIZE;                }                name->bytes[name->length-2] = '/r';                name->bytes[name->length-1] = '/n';            }            tcp_write(pcb, HELLO, strlen(HELLO), 1);            tcp_write(pcb, name->bytes, name->length, TCP_WRITE_FLAG_COPY);            printf("/n/rGigadevice/n/rTelnet %s %s", HELLO, name->bytes);            name->length = 0;        }            /* End of processing, we free the pbuf */        pbuf_free(p);    }      else if (err == ERR_OK)     {        /* When the pbuf is NULL and the err is ERR_OK, the remote end            is closing the connection. */        /* We free the allocated memory and we close the connection */        mem_free(name);        return tcp_close(pcb);    }    return ERR_OK;}
开发者ID:codingzhouk,项目名称:LiteOS_Kernel,代码行数:84,


示例21: http_sendfile

unsigned int http_sendfile(unsigned int idx, const char *name, unsigned char *tx){  unsigned int len=0, i;  if(name) //start transfer -> add http header  {    http_table[idx].status = HTTP_SEND;    http_table[idx].file   = http_fid(name, &http_table[idx].fparam);    http_table[idx].ftype  = http_ftype(http_table[idx].file);    http_table[idx].flen   = http_flen(http_table[idx].file, http_table[idx].fparam);    http_table[idx].fpos   = 0;    http_table[idx].fparse = 0;    if(http_table[idx].flen == 0) //file not found    {      http_table[idx].status = HTTP_CLOSED;      len = sprintf((char*)tx, HTTP_404_HEADER"Error 404 Not found/r/n/r/n");      tcp_send(idx, len, 0);      tcp_close(idx);      return len;    }    else //file found -> send http header    {      switch(http_table[idx].ftype)      {        case HTML_FILE:          len = sprintf((char*)tx, HTTP_HTML_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case XML_FILE:          len = sprintf((char*)tx, HTTP_XML_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case JS_FILE:          len = sprintf((char*)tx, HTTP_JS_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case CSS_FILE:          len = sprintf((char*)tx, HTTP_CSS_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case TXT_FILE:          len = sprintf((char*)tx, HTTP_TXT_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case ICON_FILE:          len = sprintf((char*)tx, HTTP_ICON_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case GIF_FILE:          len = sprintf((char*)tx, HTTP_GIF_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;        case JPEG_FILE:          len = sprintf((char*)tx, HTTP_JPEG_HEADER"%i/r/n/r/n", http_table[idx].flen);          tx += len;          break;      }    }  }  if(http_table[idx].flen) //file found  {    switch(http_table[idx].ftype)    {      //dynamic content      case HTML_FILE:      case XML_FILE:        i = http_fparse((char*)tx, http_table[idx].file, &http_table[idx].fparse, (ETH_MTUSIZE-IP_HEADERLEN-TCP_HEADERLEN-MAX_ADDR-100), http_table[idx].fparam);        http_table[idx].fpos += i;        len += i;        break;      //static content      case JS_FILE:      case CSS_FILE:      case TXT_FILE:      case ICON_FILE:      case GIF_FILE:      case JPEG_FILE:        i = http_fdata(tx, http_table[idx].file, http_table[idx].fpos, (ETH_MTUSIZE-IP_HEADERLEN-TCP_HEADERLEN-MAX_ADDR-100));        http_table[idx].fpos += i;        len += i;        break;    }    tcp_send(idx, len, 0);    if((http_table[idx].fpos >= http_table[idx].flen) || (len == 0))    {      http_close(idx);      tcp_close(idx);    }  }  return len;}
开发者ID:Bob4ik888,项目名称:WebRadio,代码行数:94,


示例22: main

int main(void){	int ret, sd, ii;	gnutls_session_t session;	char buffer[MAX_BUF + 1];	gnutls_certificate_credentials_t xcred;	// Allow connections to servers that have X509	const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };	gnutls_global_init();	gnutls_global_set_log_function(tls_log_func);	gnutls_global_set_log_level(2);	// X509 stuff	gnutls_certificate_allocate_credentials(&xcred);	// sets the trusted cas file//	gnutls_certificate_set_x509_trust_file(xcred, CAFILE,//					       GNUTLS_X509_FMT_PEM);	// Initialize TLS session 	gnutls_init(&session, GNUTLS_CLIENT);	// Use default priorities	gnutls_set_default_priority(session);	gnutls_certificate_type_set_priority(session, cert_type_priority);	// put the x509 credentials to the current session	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);	// connect to the peer	sd = tcp_connect();	// pass the socket descriptor in non blocking	tcp_nonblock(sd);	// set all the custom read/write function	gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) sd);	gnutls_transport_set_pull_function(session, tcp_read);	gnutls_transport_set_push_function(session, tcp_write);	// Perform the TLS handshake - until completed or error	do {		ret = gnutls_handshake(session);		if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)			usleep(1000 * 10);	}	while(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);	if(ret < 0) {		fprintf(stderr, "*** Handshake failed/n");		goto end;	} else {		printf("- Handshake was completed/n");	}		// log to debug	print_info(session);	ssize_t		written_len;	written_len	= gnutls_record_send(session, MSG, strlen(MSG));	printf("written_len=%d/n", written_len);	do{		ret = gnutls_record_recv(session, buffer, MAX_BUF);		if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)			usleep(1000 * 10);	}while(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);	if(ret == 0) {		printf("- Peer has closed the TLS connection/n");		goto end;	} else if(ret < 0) {		fprintf(stderr, "*** Error: %s/n", gnutls_strerror(ret));		goto end;	}	printf("- Received %d bytes: ", ret);	for(ii = 0; ii < ret; ii++) {		fputc(buffer[ii], stdout);	}	fputs("/n", stdout);	gnutls_bye(session, GNUTLS_SHUT_RDWR);      end:	tcp_close(sd);	gnutls_deinit(session);	gnutls_certificate_free_credentials(xcred);	gnutls_global_deinit();	return 0;}
开发者ID:jeromeetienne,项目名称:neoip,代码行数:92,


示例23: main

int main(void){	/* credentials */	gnutls_anon_client_credentials_t c_anoncred;	gnutls_certificate_credentials_t c_certcred;	gnutls_session_t client;	int sd, i;	/* General init. */	global_init();	ecore_init();//  gnutls_global_set_log_function (tls_log_func);//  gnutls_global_set_log_level (6);	/* Init client */	gnutls_anon_allocate_client_credentials(&c_anoncred);	gnutls_certificate_allocate_credentials(&c_certcred);	for (i = 0; i < 5; i++) {		gnutls_init(&client, GNUTLS_CLIENT);		/* set very specific priorities */		gnutls_handshake_set_timeout(client, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);		gnutls_priority_set_direct(client, "NORMAL:+ANON-DH",					   NULL);		gnutls_credentials_set(client, GNUTLS_CRD_ANON,				       c_anoncred);		gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE,				       c_certcred);		gnutls_server_name_set(client, GNUTLS_NAME_DNS,				       "localhost", strlen("localhost"));		/* connect to the peer		 */		sd = tcp_connect();		/* associate gnutls with socket */		gnutls_transport_set_int(client, sd);		/* add a callback for data being available for send/receive on socket */		if (!ecore_main_fd_handler_add		    (sd, ECORE_FD_READ | ECORE_FD_WRITE,		     (Ecore_Fd_Cb) _process_data, client, NULL, NULL)) {			print("could not create fd handler!");			exit(1);		}		/* begin main loop */		ecore_main_loop_begin();		gnutls_bye(client, GNUTLS_SHUT_RDWR);		gnutls_deinit(client);		tcp_close(sd);	}	gnutls_anon_free_client_credentials(c_anoncred);	gnutls_certificate_free_credentials(c_certcred);	return 0;}
开发者ID:GostCrypt,项目名称:GnuTLS,代码行数:64,


示例24: usys_accept

int usys_accept(int *err, uuprocess_t *u, int fd, struct sockaddr *acc_addr, socklen_t *addrlen){    if( u == 0 )    {        *err = ENOTSOCK; // TODO correct?        return -1;    }    CHECK_FD(fd);    struct uufile *f = GETF(fd);    struct uusocket *us = f->impl;    // todo require UU_FILE_FLAG_ACCEPTABLE    if( ! (f->flags & (UU_FILE_FLAG_NET|UU_FILE_FLAG_TCP)) )    {        *err = ENOTSOCK;        return -1;    }    //us->addr = my_addr;    void *new_socket = NULL;    i4sockaddr tmp_addr;    int pe = tcp_accept(us->prot_data, &tmp_addr, &new_socket);    if( *addrlen >= (int)sizeof(struct sockaddr_in) )    {        /*        struct sockaddr_in ia;        ia.sin_len = sizeof(struct sockaddr_in);        ia.sin_port = tmp_addr.port;        ia.sin_addr.s_addr = NETADDR_TO_IPV4(tmp_addr.addr);        ia.sin_family = PF_INET;        *((struct sockaddr_in *)acc_addr) = ia;        *addrlen = sizeof(struct sockaddr_in);        */        if( sockaddr_int2unix( acc_addr, addrlen, &tmp_addr ) )            *addrlen = 0;    }    else        *addrlen = 0;    // TODO translate!    if( pe )    {        *err = ECONNABORTED;        return -1;    }    struct uusocket *rus = calloc(1, sizeof(struct uusocket));    if(rus == 0)    {        tcp_close( new_socket );        *err = ENOMEM;        return -1;    }    uufile_t *rf = create_uufile();    assert(f);    rf->ops = &tcpfs_fops;    rf->pos = 0;    rf->fs = &tcp_fs;    rf->impl = rus;    rf->flags = UU_FILE_FLAG_NET|UU_FILE_FLAG_TCP;    int rfd = uu_find_fd( u, rf );    if( rfd < 0 )    {        tcp_close( new_socket );        unlink_uufile( f );        free( us );        *err = EMFILE;        return -1;    }    return *err ? -1 : rfd;}
开发者ID:agileinsider,项目名称:phantomuserland,代码行数:86,


示例25: tcp_timer_2msl

voidtcp_timer_2msl(void *xtp){	struct tcpcb *tp = xtp;	struct inpcb *inp;	CURVNET_SET(tp->t_vnet);#ifdef TCPDEBUG	int ostate;	ostate = tp->t_state;#endif	INP_INFO_RLOCK(&V_tcbinfo);	inp = tp->t_inpcb;	KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));	INP_WLOCK(inp);	tcp_free_sackholes(tp);	if (callout_pending(&tp->t_timers->tt_2msl) ||	    !callout_active(&tp->t_timers->tt_2msl)) {		INP_WUNLOCK(tp->t_inpcb);		INP_INFO_RUNLOCK(&V_tcbinfo);		CURVNET_RESTORE();		return;	}	callout_deactivate(&tp->t_timers->tt_2msl);	if ((inp->inp_flags & INP_DROPPED) != 0) {		INP_WUNLOCK(inp);		INP_INFO_RUNLOCK(&V_tcbinfo);		CURVNET_RESTORE();		return;	}	KASSERT((tp->t_timers->tt_flags & TT_STOPPED) == 0,		("%s: tp %p tcpcb can't be stopped here", __func__, tp));	KASSERT((tp->t_timers->tt_flags & TT_2MSL) != 0,		("%s: tp %p 2msl callout should be running", __func__, tp));	/*	 * 2 MSL timeout in shutdown went off.  If we're closed but	 * still waiting for peer to close and connection has been idle	 * too long delete connection control block.  Otherwise, check	 * again in a bit.	 *	 * If in TIME_WAIT state just ignore as this timeout is handled in	 * tcp_tw_2msl_scan().	 *	 * If fastrecycle of FIN_WAIT_2, in FIN_WAIT_2 and receiver has closed, 	 * there's no point in hanging onto FIN_WAIT_2 socket. Just close it. 	 * Ignore fact that there were recent incoming segments.	 */	if ((inp->inp_flags & INP_TIMEWAIT) != 0) {		INP_WUNLOCK(inp);		INP_INFO_RUNLOCK(&V_tcbinfo);		CURVNET_RESTORE();		return;	}	if (tcp_fast_finwait2_recycle && tp->t_state == TCPS_FIN_WAIT_2 &&	    tp->t_inpcb && tp->t_inpcb->inp_socket && 	    (tp->t_inpcb->inp_socket->so_rcv.sb_state & SBS_CANTRCVMORE)) {		TCPSTAT_INC(tcps_finwait2_drops);		tp = tcp_close(tp);             	} else {		if (ticks - tp->t_rcvtime <= TP_MAXIDLE(tp)) {			if (!callout_reset(&tp->t_timers->tt_2msl,			   TP_KEEPINTVL(tp), tcp_timer_2msl, tp)) {				tp->t_timers->tt_flags &= ~TT_2MSL_RST;			}		} else		       tp = tcp_close(tp);       }#ifdef TCPDEBUG	if (tp != NULL && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))		tcp_trace(TA_USER, ostate, tp, (void *)0, (struct tcphdr *)0,			  PRU_SLOWTIMO);#endif	TCP_PROBE2(debug__user, tp, PRU_SLOWTIMO);	if (tp != NULL)		INP_WUNLOCK(inp);	INP_INFO_RUNLOCK(&V_tcbinfo);	CURVNET_RESTORE();}
开发者ID:woodsb02,项目名称:freebsd-base-graphics,代码行数:80,


示例26: tcp_connect

//.........这里部分代码省略.........	return NULL;      }      getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen);    } else {      err = errno;    }  } else {    err = 0;  }  if(err != 0) {    snprintf(errbuf, errbufsize, "%s", strerror(err));    close(fd);    return NULL;  }    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);  val = 1;  setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));  tcpcon_t *tc = calloc(1, sizeof(tcpcon_t));  tc->fd = fd;  htsbuf_queue_init(&tc->spill, 0);    if(ssl) {#if ENABLE_OPENSSL    if(showtime_ssl_ctx != NULL) {      char errmsg[120];      if((tc->ssl = SSL_new(showtime_ssl_ctx)) == NULL) {	ERR_error_string(ERR_get_error(), errmsg);	snprintf(errbuf, errlen, "SSL: %s", errmsg);	tcp_close(tc);	return NULL;      }      if(SSL_set_fd(tc->ssl, tc->fd) == 0) {	ERR_error_string(ERR_get_error(), errmsg);	snprintf(errbuf, errlen, "SSL fd: %s", errmsg);	tcp_close(tc);	return NULL;      }      if(SSL_connect(tc->ssl) <= 0) {	ERR_error_string(ERR_get_error(), errmsg);	snprintf(errbuf, errlen, "SSL connect: %s", errmsg);	tcp_close(tc);	return NULL;      }      SSL_set_mode(tc->ssl, SSL_MODE_AUTO_RETRY);      tc->read = ssl_read;      tc->write = ssl_write;    } else#elif ENABLE_POLARSSL    if(1) {      tc->ssl = malloc(sizeof(ssl_context));      if(ssl_init(tc->ssl)) {	snprintf(errbuf, errlen, "SSL failed to initialize");	close(fd);	free(tc->ssl);	free(tc);	return NULL;      }      tc->ssn = malloc(sizeof(ssl_session));      tc->hs = malloc(sizeof(havege_state));      havege_init(tc->hs);      memset(tc->ssn, 0, sizeof(ssl_session));      ssl_set_endpoint(tc->ssl, SSL_IS_CLIENT );      ssl_set_authmode(tc->ssl, SSL_VERIFY_NONE );      ssl_set_rng(tc->ssl, havege_rand, tc->hs );      ssl_set_bio(tc->ssl, net_recv, &tc->fd, net_send, &tc->fd);      ssl_set_ciphers(tc->ssl, ssl_default_ciphers );      ssl_set_session(tc->ssl, 1, 600, tc->ssn );            tc->read = polarssl_read;      tc->write = polarssl_write;          } else#endif    {      snprintf(errbuf, errlen, "SSL not supported");      tcp_close(tc);      return NULL;    }  } else {    tc->read = tcp_read;    tc->write = tcp_write;  }  return tc;}
开发者ID:Rautz,项目名称:showtime,代码行数:101,


示例27: client

static voidclient (void){  int ret, sd, ii;  gnutls_session_t session;  char buffer[MAX_BUF + 1];  gnutls_psk_client_credentials_t pskcred;  const gnutls_datum_t key = { (char *) "DEADBEEF", 8 };  gnutls_global_init ();  gnutls_global_set_log_function (tls_log_func);//  if (debug)//    gnutls_global_set_log_level (99);  gnutls_psk_allocate_client_credentials (&pskcred);  gnutls_psk_set_client_credentials (pskcred, "test", &key,				     GNUTLS_PSK_KEY_HEX);  /* Initialize TLS session   */  gnutls_init (&session, GNUTLS_CLIENT);  /* Use default priorities */  gnutls_set_default_priority (session);  /* put the anonymous credentials to the current session   */  gnutls_credentials_set (session, GNUTLS_CRD_PSK, pskcred);  /* connect to the peer   */  sd = tcp_connect ();  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);  /* Perform the TLS handshake   */  ret = gnutls_handshake (session);  if (ret < 0)    {      fail ("client: Handshake failed/n");      gnutls_perror (ret);      goto end;    }  else    {      if (debug)	success ("client: Handshake was completed/n");    }  gnutls_record_send (session, MSG, strlen (MSG));  ret = gnutls_record_recv (session, buffer, MAX_BUF);  if (ret == 0)    {      if (debug)	success ("client: Peer has closed the TLS connection/n");      goto end;    }  else if (ret < 0)    {      fail ("client: Error: %s/n", gnutls_strerror (ret));      goto end;    }  if (debug)    {      printf ("- Received %d bytes: ", ret);      for (ii = 0; ii < ret; ii++)	fputc (buffer[ii], stdout);      fputs ("/n", stdout);    }  gnutls_bye (session, GNUTLS_SHUT_RDWR);end:  tcp_close (sd);  gnutls_deinit (session);  gnutls_psk_free_client_credentials (pskcred);  gnutls_global_deinit ();}
开发者ID:Chronic-Dev,项目名称:gnutls,代码行数:87,


示例28: loop_process

void loop_process(int cfd) {	DEBUG(" Child=======>  In child!/n");	int acceptfd;	int recved;	fd_set readfds;	int delay = 300;	struct timeval timeout;	timeout.tv_sec = 10;	timeout.tv_usec = 0;	struct sockaddr_in client_addr;	socklen_t sock_len = sizeof(struct sockaddr);	char buffer[512];	ctl_hdr *hdr;	uint16 ret_code = 0;	//服务器对web服务器的回复报文	struct replay_packet replay;	replay.head.len = 2;	replay.head.encrpyt = ENCRPYT_NO;	replay.head.mo = MO_SERVER;	replay.head.ttl = 0;	replay.head.ki = KI_REPLAY;	while (1) {		DEBUG(" Child=======>  Waiting for connect! In child thread!/n");		FD_ZERO(&readfds);		FD_SET(cfd, &readfds);		timeout.tv_sec = delay;		timeout.tv_usec = 0;		int tt;		switch(tt = select(cfd + 1, &readfds, NULL, NULL, &timeout)) {		case -1:			//error			continue;			break;		default:			if (FD_ISSET(cfd, &readfds)) {				acceptfd = accept(cfd,(struct sockaddr *) &client_addr, &sock_len);				if (acceptfd <=0)  {					DEBUG(" Child=======>  accept failed!/n");					exit(-1);				}				recved = recv(acceptfd, buffer, sizeof(buffer), 0);				DEBUG(" Child=======>  Listen socket:  %d/tAccept socket:  %d/n", cfd, acceptfd);				struct common_packet * common = (struct common_packet *)buffer;				DEBUG(" Child=======>  Received KI:  %d/n", common->head.ki);				DEBUG(" Child=======>  Received data length:  %d/n", recved);				if (recved > 0) {					hdr = (ctl_hdr *)buffer;					//如果是登录请求					if (hdr->ki == KI_LOGIN) {						//判断用户名和密码是否正确						struct register_struct * user_struct = (struct register_struct *)buffer;						if (user_check(&(user_struct->user_struct)) == 0) {							//登录成功							replay.data = RPL_LOGIN_SUCCESS;							replay.head.extent = 111;							writen(acceptfd, (void *)&replay, sizeof(replay));							DEBUG(" Child=======>  Login successful!/n");							tcp_close(acceptfd);						} else {							replay.data = RPL_LOGIN_FALLED;							writen(acceptfd, (void *)&replay, sizeof(replay));							DEBUG(" Child=======>  Login failed!/n");							tcp_close(acceptfd);						}					} else if (hdr->ki == KI_REGISTER) {						//用户注册						struct register_struct * user_struct = (struct register_struct *)buffer;						if (user_register(&(user_struct->user_struct)) == 0) {							//注册成功							replay.data = RPL_REGISTER_SUCCESS;							writen(acceptfd, (void *)&replay, sizeof(replay));							DEBUG("Register User Successful/n");							tcp_close(acceptfd);						} else {							replay.data = RPL_REGISTER_FALLED;							writen(acceptfd, (void *)&replay, sizeof(replay));							DEBUG("Register User Failed/n");							tcp_close(acceptfd);						}						//如果是发送的数据包,判断extent值,看是否已登录成功					} else {						hdr = (ctl_hdr *)buffer;						DEBUG(" Child=======>  extent is : %d/tttl is : %d/n", hdr->extent, hdr->ttl);						if ((hdr->extent) == 111) {							ret_code = proc_packet(buffer, acceptfd);							if (ret_code == RPL_NO_COMMON_REPLAY) {							} else {								replay.data = ret_code;								writen(acceptfd, (void *)&replay, sizeof(replay));							}							tcp_close(acceptfd);						}					}				}//.........这里部分代码省略.........
开发者ID:markmoon,项目名称:miniserver,代码行数:101,


示例29: start_daemon

static void start_daemon(){	// Capture USB device	struct usb_sock_t *usb_sock = usb_open();	if (usb_sock == NULL)		goto cleanup_usb;	// Capture a socket	uint32_t desired_port = g_options.desired_port;	struct tcp_sock_t *tcp_socket = tcp_open(desired_port);	if (tcp_socket == NULL)		goto cleanup_tcp;	uint32_t real_port = tcp_port_number_get(tcp_socket);	if (desired_port != 0 && desired_port != real_port) {		ERR("Received port number did not match requested port number."		    " The requested port number may be too high.");		goto cleanup_tcp;	}	printf("%u/n", real_port);	// Lose connection to caller	if (!g_options.nofork_mode && fork() > 0)		exit(0);	for (;;) {		struct service_thread_param *args = calloc(1, sizeof(*args));		if (args == NULL) {			ERR("Failed to alloc space for thread args");			goto cleanup_thread;		}		args->usb_sock = usb_sock;		args->tcp = tcp_conn_accept(tcp_socket);		if (args->tcp == NULL) {			ERR("Failed to open tcp connection");			goto cleanup_thread;		}		int status = pthread_create(&args->thread_handle, NULL,		                            &service_connection, args);		if (status) {			ERR("Failed to spawn thread, error %d", status);			goto cleanup_thread;		}		continue;	cleanup_thread:		if (args != NULL) {			if (args->tcp != NULL)				tcp_conn_close(args->tcp);			free(args);		}		break;	}cleanup_tcp:	if (tcp_socket!= NULL)		tcp_close(tcp_socket);cleanup_usb:	if (usb_sock != NULL)		usb_close(usb_sock);	return;}
开发者ID:jhcloos,项目名称:ippusbxd-gpl3,代码行数:65,



注:本文中的tcp_close函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ tcp_connect函数代码示例
C++ tcp_bind函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。