Skip to main content
oziesin
Associate III
October 27, 2022
Question

How to stop listening port on tcp communication properly with LWIP Stack ?

  • October 27, 2022
  • 3 replies
  • 2328 views

Hello, I have a mcu that works as a tcp server. I listen 2 port for connection, if i want to stop listening what must i do ?

I use this function to initialise port

void TCPServerInitialise( U16 usPort )
{
	struct tcp_pcb *pstTcp_pcb;
 
	/* create new tcp pcb */
	pstTcp_pcb = tcp_new ();	// allocate new tcp_pcb
 
	if ( pstTcp_pcb != NULL )
	{
		err_t err;
 
		/* bind pcb to port */
		err = tcp_bind ( pstTcp_pcb, IP_ADDR_ANY, usPort );
 
		CONSOLE_PRINT_1( "Tcp_Bind Err : %d", err );
 
		if ( err == ERR_OK )
		{
			/* start tcp listening for pcb */
			pstTcp_pcb = tcp_listen( pstTcp_pcb );
 
			if ( usPort == stPRM.stTransParams.st485Cfg.usETHPort )
			{
				mLedEth485StatusSet()
				stTaskETH.pst_tcp_pcb_485 = pstTcp_pcb;
			}
 
			else if ( usPort == stPRM.stTransParams.st232Cfg.usETHPort )
			{
				mLedEth232StatusSet()
				stTaskETH.pst_tcp_pcb_232 = pstTcp_pcb;
			}
			/* initialize LwIP tcp_accept callback function */
			tcp_accept ( pstTcp_pcb, TCPServerAcceptCallback );
 
			CONSOLE_PRINT_1( "Port %d is up !", usPort );
		}
		else
		{
			EventInsert( eEventTcpInitFail );
			/* deallocate the pcb */
			memp_free ( MEMP_TCP_PCB, pstTcp_pcb );
		}
	}
}

I tried tcp_close ( stTaskETH.pst_tcp_pcb_232 ); and tcp_close ( stTaskETH.pst_tcp_pcb_232 ); but still i have issues tcp_close didnt clear variables.

This topic has been closed for replies.

3 replies

Bob S
Super User
October 27, 2022

What about "tcp_close( pstTcp_pcb )" (i.e. close the instance that you are "listening" with? When you close the pcb that you get from the "accept" call, the "listen" pcb is still active.

Piranha
Principal III
October 27, 2022

A very important question - does the project use RTOS? Also take a note that tcp_close() is not guaranteed to succeed.

By the way else if in the line 28 doesn't make sense. Take the if part away or introduce the third option with just an else.

oziesin
oziesinAuthor
Associate III
October 31, 2022

No, Project does not use RTOS. 

I use tcpcloseCallback function like below.

void TCPServerConnectCloseCallback( struct tcp_pcb *pstTpcb, struct echoserver *pstEs )
 {
	 if( pstTpcb == stTaskETH.pstEs485->pcb )
	 {
		 stTaskETH.pstEs485 = NULL; // must be here
		 mLedEth485StatusClear();
	 }
	 else if( pstTpcb == stTaskETH.pstEs232->pcb )
	 {
		 stTaskETH.pstEs232 = NULL; // must be here
		 mLedEth232StatusClear();
	 }
	 /* remove all callbacks */
 tcp_arg(pstTpcb, NULL);
 tcp_sent(pstTpcb, NULL);
 tcp_recv(pstTpcb, NULL);
 tcp_err(pstTpcb, NULL);
 tcp_poll(pstTpcb, NULL, 0);
 
 /* delete pstEs structure */
 if (pstEs != NULL)
 {
 mem_free(pstEs);
 }
 
 /* close tcp connection */
 tcp_close(pstTpcb);
 }

This function always close connection successfully from client side but i cannot close port listening. I hope i could explain clearly