tcp

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 13, 2026 License: MIT Imports: 14 Imported by: 21 modules, 18 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

TCP Checker 💓

Go Report Card GoDoc Build Status

This package is used to perform TCP handshake without ACK, which useful for TCP health checking.

HAProxy does this exactly the same, which is:

  1. SYN
  2. SYN-ACK
  3. RST

This implementation has been running on tens of thousands of production servers for years.

Why do I have to do this

In most cases when you establish a TCP connection(e.g. via net.Dial), these are the first three packets between the client and server(TCP three-way handshake):

  1. Client -> Server: SYN
  2. Server -> Client: SYN-ACK
  3. Client -> Server: ACK

This package tries to avoid the last ACK when doing handshakes.

By sending the last ACK, the connection is considered established.

However, as for TCP health checking the server could be considered alive right after it sends back SYN-ACK,

that renders the last ACK unnecessary or even harmful in some cases.

Benefits

By avoiding the last ACK

  1. Less packets better efficiency
  2. The health checking is less obvious

The second one is essential because it bothers the server less.

This means the application level server will not notice the health checking traffic at all, thus the act of health checking will not be considered as some misbehavior of client.

Requirements

  • Linux 2.4 or newer

There is a fake implementation for non-Linux platform which is equivalent to:

conn, err := net.DialTimeout("tcp", addr, timeout)
conn.Close()

The reason for a fake implementation is that there is currently no way to perform an equivalent operation on certain platforms, specifically macOS. A fake implementation is a degradation on those platforms and ensures a successful compilation.

Usage

import (
	tcpshaker "github.com/tevino/tcp-shaker"
)

// Get the global singleton Checker instance
checker := tcpshaker.DefaultChecker()


// Checking example.com
err := checker.CheckAddr("example.com:80", time.Second)
switch err {
case ErrTimeout:
	fmt.Println("Connect timed out after 1s")
case nil:
	fmt.Println("Connect succeeded")
default:
	fmt.Println("Error occurred while connecting: ", err)
}
Manual initialization

For fine-grained control of the lifecycle of the Checker.

// Initializing the checker
// Only a single instance is needed and it's safe to use among goroutines.
checker := NewChecker()

ctx, stopChecker := context.WithCancel(context.Background())
defer stopChecker()
go func() {
	if err := checker.CheckingLoop(ctx); err != nil {
		fmt.Println("checking loop stopped due to fatal error: ", err)
	}
}()

<-checker.WaitReady()

// now the checker could be used as shown in the previous example.
Command-line tool

A tcp-checker command-line tool is also available. It can be built with:

go build -o tcp-checker ./cmd/tcp-checker

Or installed directly using go install:

go install github.com/tevino/tcp-shaker/cmd/tcp-checker

Example usage:

# Check example.com:443 with a 2 seconds timeout
tcp-checker -a example.com:443 -t 2000

Development & Contributing

See CONTRIBUTING.md to learn how to contribute to the project.

TODO

  • IPv6 support (Test environment needed, PRs are welcome)

Special thanks to contributors

  • @lujjjh Added zero linger support for non-Linux platform
  • @jakubgs Fixed compatibility on Android
  • @kirk91 Added support for IPv6
  • @eos175 Added a global singleton for Checker
  • @Lan-ce-lot Added IPv4/IPv6 network selection

Documentation

Overview

Package tcp is used to perform TCP handshake without ACK, which useful for TCP health checking. HAProxy does this exactly the same, which is:

  1. SYN
  2. SYN-ACK
  3. RST

Why do I have to do this

In most cases when you establish a TCP connection(e.g. via net.Dial), these are the first three packets between the client and server(TCP three-way handshake):

  1. Client -> Server: SYN
  2. Server -> Client: SYN-ACK
  3. Client -> Server: ACK

This package tries to avoid the last ACK when doing handshakes.

By sending the last ACK, the connection is considered established.

However, as for TCP health checking the server could be considered alive right after it sends back SYN-ACK, that renders the last ACK unnecessary or even harmful in some cases.

Benefits

By avoiding the last ACK

  1. Less packets better efficiency
  2. The health checking is less obvious

The second one is essential because it bothers the server less.

This means the application level server will not notice the health checking traffic at all, thus the act of health checking will not be considered as some misbehavior of client.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrCheckerAlreadyStarted = errors.New("Checker was already started")

ErrCheckerAlreadyStarted indicates there is another instance of CheckingLoop running.

View Source
var ErrTimeout = &timeoutError{}

ErrTimeout indicates I/O timeout

Functions

This section is empty.

Types

type Checker

type Checker struct {
	// contains filtered or unexported fields
}

Checker contains an epoll instance for TCP handshake checking. NOTE: Ideally only one instance of Checker should be created within a process.

Example
c := NewChecker()

ctx, stopChecker := context.WithCancel(context.Background())
defer stopChecker()
go func() {
	if err := c.CheckingLoop(ctx); err != nil {
		fmt.Println("checking loop stopped due to fatal error: ", err)
	}
}()

<-c.WaitReady()

timeout := time.Second * 1
err := c.CheckAddr("example.com:80", timeout)
switch err {
case ErrTimeout:
	fmt.Println("Connect timed out")
case nil:
	fmt.Println("Connect succeeded")
default:
	fmt.Println("Error occurred while connecting: ", err)
}

func DefaultChecker

func DefaultChecker() *Checker

DefaultChecker returns a shared singleton instance of the Checker.

It starts the Checker's CheckingLoop in a goroutine with a context that listens for system signals (SIGINT, SIGTERM) to stop gracefully. This function blocks until the Checker is ready for use.

func NewChecker

func NewChecker() *Checker

NewChecker creates a Checker with linger set to zero.

func NewCheckerZeroLinger

func NewCheckerZeroLinger(zeroLinger bool) *Checker

NewCheckerZeroLinger creates a Checker with zeroLinger set to given value.

func (*Checker) CheckAddr

func (c *Checker) CheckAddr(addr string, timeout time.Duration) (err error)

CheckAddr performs a TCP check with given TCP address and timeout A successful check will result in nil error ErrTimeout is returned if timeout zeroLinger is an optional parameter indicating if linger should be set to zero for this particular connection Note: timeout includes domain resolving

func (*Checker) CheckAddrWithOptions

func (c *Checker) CheckAddrWithOptions(addr string, opts Options) error

CheckAddrWithOptions performs a TCP check with given address and options. A successful check will result in nil error. ErrTimeout is returned if timeout. Note: timeout includes domain resolving.

func (*Checker) CheckAddrZeroLinger

func (c *Checker) CheckAddrZeroLinger(addr string, timeout time.Duration, zeroLinger bool) error

CheckAddrZeroLinger is like CheckAddr with an extra parameter indicating whether to enable zero linger.

func (*Checker) CheckingLoop

func (c *Checker) CheckingLoop(ctx context.Context) error

CheckingLoop must be called before anything else. NOTE: this function blocks until ctx got canceled.

func (*Checker) IsReady

func (c *Checker) IsReady() bool

IsReady returns a bool indicates whether the Checker is ready for use

func (*Checker) PollerFd

func (c *Checker) PollerFd() int

PollerFd returns the inner fd of poller instance. NOTE: Use this only when you really know what you are doing.

func (*Checker) WaitReady

func (c *Checker) WaitReady() <-chan struct{}

WaitReady returns a chan which is closed when the Checker is ready for use.

type ErrConnect

type ErrConnect struct {
	// contains filtered or unexported fields
}

ErrConnect is an error occurs while connecting to the host To get the detail of underlying error, lookup ErrorCode() in 'man 2 connect'

type Options

type Options struct {
	// Timeout specifies the maximum duration for the check operation
	Timeout time.Duration

	// Network specifies the network type for address resolution and connection.
	//
	// Supported values:
	//   "tcp4"   IPv4 only.
	//   "tcp6"   IPv6 only.
	//   "tcp"    Default. Accepts both IPv4 and IPv6.
	//
	//   - IP literal:      the address family matches the literal.
	//   - Hostname+tcp4/6: only the requested record type (A/AAAA)
	//                      is resolved.
	//   - Hostname+tcp:    resolved to whichever IP the system DNS
	//                      resolver returns first (as of Go 1.26).
	//
	// Only that one address is tried; there is no fallback between
	// IPv4 and IPv6.
	Network string

	// ZeroLinger indicates whether to set SO_LINGER with zero timeout
	// This forces the connection to be reset immediately when closed
	ZeroLinger bool
}

Options contains configuration for TCP connectivity checks

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns Options with default values

func (Options) WithNetwork

func (o Options) WithNetwork(network string) Options

WithNetwork sets the network type (tcp, tcp4, tcp6)

func (Options) WithTimeout

func (o Options) WithTimeout(timeout time.Duration) Options

WithTimeout sets the timeout for the operation

func (Options) WithZeroLinger

func (o Options) WithZeroLinger(zeroLinger bool) Options

WithZeroLinger sets the zero linger option

Directories

Path Synopsis
cmd
tcp-checker command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址