netutil

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 7 Imported by: 0

README

netutil

Network utilities: port availability, IP address helpers, HTTP client with retry, and TCP/UDP utilities.

Features

  • Port availability: check, find, and allocate free ports (TCP/UDP)
  • IP address helpers: local, outbound, public, private/loopback detection
  • HTTP client with configurable retry, timeout, and circuit breaker
  • TCP/UDP utilities: dial, listen, ping, forward

Key types

  • HTTPClientConfig -- HTTP client settings (timeout, max retries, retry interval, circuit breaker)
  • CircuitBreakerConfig -- circuit breaker thresholds and cooldown

Key functions

  • IsPortAvailable(network, port), IsTCPPortAvailable(port), IsUDPPortAvailable(port)
  • FreePort(), FreeUDPPort(), FindAvailablePort(start, end), FindAvailablePorts(start, n)
  • LocalIP(), LocalIPs(), LocalIPv6s(), AllIPs(), OutboundIP(target)
  • PublicIP(), IsPrivateIP(ipStr), IsLoopback(ipStr), IsPublicIP(ipStr)
  • IPRange(cidr) -- start and end IPs of a CIDR range
  • NewHTTPClient(cfg) -- HTTP client with retry and circuit breaker
  • DialTCP, ListenTCP, Ping, ForwardTCP -- low-level TCP utilities

Quick start

import (
    "time"
    "github.com/LingByte/ling-base/common/netutil"
)

// Check if a port is available
ok := netutil.IsPortAvailable("tcp", 8080)

// Get local IP
ip := netutil.LocalIP()

// HTTP client with retry
client := netutil.NewHTTPClient(netutil.HTTPClientConfig{
    Timeout:       10 * time.Second,
    MaxRetries:    3,
    RetryInterval: time.Second,
})
resp, err := client.Get("https://example.com")

License

MIT

Documentation

Overview

Package netutil provides network utilities:

  • Port availability: IsPortAvailable, FindAvailablePort, FreePort
  • IP address helpers: LocalIPs, PublicIP, IsPrivateIP, IsLoopback
  • HTTP client with retry, timeout, and circuit breaker
  • TCP/UDP utilities: dial, listen, ping, forward

Quick start

// Check if a port is available
ok := netutil.IsPortAvailable("tcp", 8080)

// Get local IP
ip := netutil.LocalIP()

// HTTP client with retry
client := netutil.NewHTTPClient(netutil.HTTPClientConfig{
    Timeout:       10 * time.Second,
    MaxRetries:    3,
    RetryInterval: time.Second,
})
resp, err := client.Get("https://example.com")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllIPs

func AllIPs() []string

AllIPs returns all IP addresses (v4 and v6) including loopback.

func FindAvailablePort

func FindAvailablePort(start, end int) (int, error)

FindAvailablePort finds the first available TCP port starting from start. Returns an error if no port is found within [start, end].

func FindAvailablePorts

func FindAvailablePorts(start, n int) ([]int, error)

FindAvailablePorts finds n available TCP ports starting from start.

func FreePort

func FreePort() (int, error)

FreePort returns a free TCP port provided by the OS. The port is not reserved; another process may grab it.

func FreeUDPPort

func FreeUDPPort() (int, error)

FreeUDPPort returns a free UDP port provided by the OS.

func IPRange

func IPRange(cidr string) (start, end string, err error)

IPRange returns the start and end IPs of a CIDR range. Returns an error if the CIDR is invalid.

func InterfaceIPs

func InterfaceIPs(name string) ([]string, error)

InterfaceIPs returns all IP addresses for the named interface.

func Interfaces

func Interfaces() ([]string, error)

Interfaces returns all network interface names.

func IsLoopback

func IsLoopback(ipStr string) bool

IsLoopback returns true if the IP is a loopback address.

func IsPortAvailable

func IsPortAvailable(network string, port int) bool

IsPortAvailable checks if a TCP/UDP port is available on localhost.

func IsPrivateIP

func IsPrivateIP(ipStr string) bool

IsPrivateIP returns true if the IP is in a private range. Private ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7.

func IsPublicIP

func IsPublicIP(ipStr string) bool

IsPublicIP returns true if the IP is not private and not loopback.

func IsTCPPortAvailable

func IsTCPPortAvailable(port int) bool

IsTCPPortAvailable checks if a TCP port is available.

func IsTCPReachable

func IsTCPReachable(addr string, timeout time.Duration) bool

IsTCPReachable returns true if a TCP address is reachable.

func IsUDPPortAvailable

func IsUDPPortAvailable(port int) bool

IsUDPPortAvailable checks if a UDP port is available.

func LocalIP

func LocalIP() string

LocalIP returns the first non-loopback IPv4 address of the machine. Returns "" if no non-loopback address is found.

func LocalIPs

func LocalIPs() []string

LocalIPs returns all non-loopback IPv4 addresses of the machine.

func LocalIPv6s

func LocalIPv6s() []string

LocalIPv6s returns all non-loopback IPv6 addresses of the machine.

func LookupCNAME

func LookupCNAME(hostname string) (string, error)

LookupCNAME resolves the CNAME record for a hostname.

func LookupHost

func LookupHost(hostname string) ([]string, error)

LookupHost resolves a hostname to IP addresses.

func LookupMX

func LookupMX(domain string) ([]*net.MX, error)

LookupMX resolves MX records for a domain.

func LookupTXT

func LookupTXT(domain string) ([]string, error)

LookupTXT resolves TXT records for a domain.

func MACAddress

func MACAddress(name string) (string, error)

MACAddress returns the MAC address of the named interface. Returns "" if the interface has no MAC address.

func NewStandardHTTPClient added in v0.2.0

func NewStandardHTTPClient(cfg HTTPClientConfig) *http.Client

NewStandardHTTPClient returns a plain *http.Client configured with timeout, transport, redirect policy and cookie jar from cfg. Unlike NewHTTPClient it does NOT wrap the client with retry or circuit-breaker logic — useful for callers (e.g. security scanners) that need to observe raw responses without retry masking.

func OutboundIP

func OutboundIP(target string) (string, error)

OutboundIP returns the local IP address used to reach the given target. If target is empty, it uses "8.8.8.8:80" as a public target.

func PublicIP

func PublicIP() string

PublicIP fetches the public IP address using an external service. Uses https://api.ipify.org by default. Returns "" on error.

func PublicIPWithProvider

func PublicIPWithProvider(url string) string

PublicIPWithProvider fetches the public IP using the given provider URL. The response body should be just the IP address.

func ResolveIP

func ResolveIP(hostname string) string

ResolveIP resolves a hostname to a single IPv4 address. Returns "" if no IPv4 address is found.

func TCPConnect

func TCPConnect(addr string, timeout time.Duration) error

TCPConnect attempts to connect to a TCP address with a timeout. Returns nil if connection succeeds.

func TCPExchange

func TCPExchange(addr string, data []byte, timeout time.Duration) ([]byte, error)

TCPExchange connects to a TCP address, sends data, and reads the response. Returns the response bytes.

func TCPForward

func TCPForward(dst, src net.Conn) error

TCPForward forwards data between two TCP connections (bidirectional). Blocks until either connection is closed.

func TCPPing

func TCPPing(addr string, timeout time.Duration) (time.Duration, error)

TCPPing checks if a TCP address is reachable within the timeout. Returns the round-trip duration.

func UDPExchange

func UDPExchange(addr string, data []byte, timeout time.Duration) ([]byte, error)

UDPExchange sends data to a UDP address and reads the response.

func UDPSend

func UDPSend(addr string, data []byte) error

UDPSend sends data to a UDP address without waiting for a response.

Types

type CircuitBreaker

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

CircuitBreaker implements a simple circuit breaker.

func NewCircuitBreaker

func NewCircuitBreaker(threshold int, timeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a circuit breaker that opens after threshold consecutive failures and stays open for timeout before entering half-open.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow returns true if a request is allowed through.

func (*CircuitBreaker) Failures

func (cb *CircuitBreaker) Failures() int

Failures returns the current failure count.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request.

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker to closed state.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current circuit breaker state.

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker.

const (
	CircuitClosed   CircuitState = iota // normal operation
	CircuitOpen                         // rejecting requests
	CircuitHalfOpen                     // testing if service is back
)

type HTTPClient

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

HTTPClient wraps http.Client with retry and circuit breaker support.

func NewHTTPClient

func NewHTTPClient(cfg HTTPClientConfig) *HTTPClient

NewHTTPClient creates a new retry-enabled HTTP client.

func (*HTTPClient) Do

func (c *HTTPClient) Do(req *http.Request) (*http.Response, error)

Do executes an HTTP request with retry logic.

func (*HTTPClient) Get

func (c *HTTPClient) Get(url string) (*http.Response, error)

Get sends a GET request.

func (*HTTPClient) GetWithContext

func (c *HTTPClient) GetWithContext(ctx context.Context, url string) (*http.Response, error)

GetWithContext sends a GET request with context.

func (*HTTPClient) Post

func (c *HTTPClient) Post(url, contentType string, body io.Reader) (*http.Response, error)

Post sends a POST request.

func (*HTTPClient) PostWithContext

func (c *HTTPClient) PostWithContext(ctx context.Context, url, contentType string, body io.Reader) (*http.Response, error)

PostWithContext sends a POST request with context.

type HTTPClientConfig

type HTTPClientConfig struct {
	Timeout         time.Duration                                      // total request timeout (default 30s)
	MaxRetries      int                                                // max retry attempts (default 3)
	RetryInterval   time.Duration                                      // base interval between retries (default 1s)
	RetryMaxWait    time.Duration                                      // max wait between retries (default 30s)
	RetryableStatus map[int]bool                                       // status codes that trigger retry (default 429, 500, 502, 503, 504)
	Transport       *http.Transport                                    // custom transport (optional)
	CircuitBreaker  *CircuitBreaker                                    // optional circuit breaker
	CheckRedirect   func(req *http.Request, via []*http.Request) error // optional redirect policy
	Jar             http.CookieJar                                     // optional cookie jar
}

HTTPClientConfig configures the retry HTTP client.

Jump to

Keyboard shortcuts

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