Sample code for 30+ languages & platforms
Xbase++

Stop an SSH Tunnel Listener (StopAccepting)

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.StopAccepting method, which stops the local listener so no new client connections are accepted. The only argument (waitForThread) selects whether to wait for the listener thread to exit. Existing forwarded clients remain connected.

Background: The distinction from CloseTunnel is the point: StopAccepting closes only the front door, leaving already-connected clients to finish their transfers undisturbed. That makes it the graceful way to drain a tunnel — stop taking new work, let existing work complete, then close — rather than cutting everyone off at once.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oTunnel
LOCAL nSshPort
LOCAL cPassword
LOCAL nListenPort
LOCAL nWaitForThread
LOCAL nWaitForThreadExit

nSuccess := 0

//  Demonstrates the SshTunnel.StopAccepting method, which stops the local listener so that no new
//  client connections are accepted.  The only argument (waitForThread) selects whether to wait for
//  the listener thread to exit.  Existing forwarded clients remain connected.

oTunnel := CreateObject("Chilkat.SshTunnel")

oTunnel:DestHostname := "db.internal.example.com"
oTunnel:DestPort := 5432

nSshPort := 22
nSuccess := oTunnel:Connect("ssh.example.com", nSshPort)
IF (nSuccess == 0)
    ? oTunnel:LastErrorText
    oTunnel:destroy()
    RETURN
ENDIF

//  Normally you would not hard-code the password in source.  You should instead obtain it
//  from an interactive prompt, environment variable, or a secrets vault.
cPassword := "mySshPassword"

nSuccess := oTunnel:AuthenticatePw("mySshLogin", cPassword)
IF (nSuccess == 0)
    ? oTunnel:LastErrorText
    oTunnel:destroy()
    RETURN
ENDIF

nListenPort := 1080
nSuccess := oTunnel:BeginAccepting(nListenPort)
IF (nSuccess == 0)
    ? oTunnel:LastErrorText
    oTunnel:destroy()
    RETURN
ENDIF

//  ... the tunnel runs for a while ...

//  Stop accepting NEW connections, but leave already-connected clients running.
nWaitForThread := 1
nSuccess := oTunnel:StopAccepting(nWaitForThread)
IF (nSuccess == 0)
    ? oTunnel:LastErrorText
    oTunnel:destroy()
    RETURN
ENDIF

? "The listener has stopped; existing clients continue."

nWaitForThreadExit := 1
nSuccess := oTunnel:CloseTunnel(nWaitForThreadExit)
IF (nSuccess == 0)
    ? oTunnel:LastErrorText
    oTunnel:destroy()
    RETURN
ENDIF

oTunnel:destroy()