snetutils

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: MIT Imports: 29 Imported by: 8

README

snetutils

Network utility library for Go — interface management, connectivity checks, DNS resolution, port scanning, mDNS/ONVIF discovery, NTP, REST API response helpers, and more.

Installation

go get github.com/sonnt85/snetutils

Features

  • Network interface information: IP, MAC, CIDR, gateway, metric, up/down state
  • IPv4/IPv6 address helpers: parse CIDR, check public/private, increment, range check
  • Connectivity checks: TCP ping, ICMP ping, online detection with retries
  • DNS resolution with fallback and debug mode
  • Route management: add/delete routes, set default gateway, DHCP renew, IP flush
  • Port utilities: check if port is open/used/available (TCP/UDP), get free port(s)
  • Service discovery: mDNS server/client, ONVIF camera discovery, CCC device discovery
  • ARP: resolve MAC address from IP (MacFromIP)
  • NetworkManager integration: connect to Wi-Fi, create hotspot
  • NTP: get network time from NTP servers or HTTP headers
  • HTTP client management: reset transport, flush connections
  • REST API response builders (HA/Cloudflare-style JSON)

Usage

import "github.com/sonnt85/snetutils"

// Get interface IPv4 address
ip, _ := snetutils.NetGetInterfaceIpv4Addr("eth0")

// Check connectivity
online := snetutils.NetIsOnline(3, 2, "eth0") // 3 tries, 2s interval

// Wait until server is reachable
err := snetutils.NetWaitServerIsOnline("8.8.8.8:53", 30*time.Second, "eth0")

// DNS resolution
addrs, _ := snetutils.ResolverDomain("example.com")
ip4, _ := snetutils.ResolverDomain2Ip4("example.com")

// ICMP ping
ipaddr, rtt, err := snetutils.Ping("192.168.1.1", "eth0", 3*time.Second)

// Port check
open := snetutils.IsPortOpen("192.168.1.1", 22, "tcp")
free, _ := snetutils.GetFreeTcpPort()

// mDNS service announcement
srv, _ := snetutils.NetInitDiscoveryServer("192.168.1.100", 8080, "device-id", "_myapp._tcp", nil, "eth0")

// mDNS discovery
entries := snetutils.NetDiscoveryQuery("_myapp._tcp", 5*time.Second, "eth0")

// ONVIF camera discovery
cameras := snetutils.OnvifDiscovery("eth0")

// IP configuration
snetutils.IpConfig("192.168.1.100", "255.255.255.0", "192.168.1.1", "eth0")

// REST API response
resp := snetutils.HABuildSuccessResponeStr(result, nil)

API

Interface & Address
  • NetGetInterfaceIpv4Addr(iface) (string, error) — interface IPv4
  • NetGetMac/NetGetMacs(iface...) — interface MAC address(es)
  • NetGetCIDR/NetGetMask/NetGetDefaultGatewayOfIface(iface...) — CIDR, mask, gateway
  • NetGetGatewayOfInterface/NetGetMetricOfInterface(iface, cidr) — routing info
  • NetInterfaceIsUp(iface) (bool, error) — interface state
  • NetGetStaticMac() string — stable MAC (loopback/first-up interface)
  • IfaceGetAllName(noLocalhost...) — list all interface names
  • GetOutboundIP/GetDefaultIface() — outbound address and default interface
  • NetGetInterfaceInfo(infotype int, ifaces...) — generic interface info by type constant
IP Utilities
  • IpBetween(from, to, test net.IP) bool — range check
  • IsPublicIP(ip net.IP) bool — public IP check
  • IpIsPrivate(ip string) bool — private range check
  • IpInc(ip net.IP) — increment IP in-place
  • IpParserCIDR(cidr string) (mask, gateway, error) — parse CIDR
  • NetIsIpv4(ip net.IP) bool — v4 check
  • NetGetInameByIP(ip string) (string, error) — reverse lookup interface name
Connectivity
  • NetIsOnline/NetIsOnlineTcp/NetIsOnlinePing(tries, interval, ifaces...) — connectivity test
  • NetWaitServerIsOnline(domain, timeout, ifaces...) — block until reachable
  • ServerIsLive(domain, ifaces...) — single connectivity check
  • Ping(addr, iface, timeout) (*net.IPAddr, time.Duration, error) — ICMP ping
  • PingExternal(domain, iface, timeout) error — system ping command
  • IsSsh/IsVnc(addr, timeout...) — protocol detection
Port
  • IsPortOpen/IsPortTcpAvailable/IsPortUdpAvailable(ip, port, timeouts...) — availability checks
  • GetFreeTcpPort/GetFreeUdpPort() (int, error) — allocate free port
  • GetFreePorts/GetFreeTcpPorts/GetFreeUdpPorts(count int) — allocate multiple ports
DNS & Routing
  • ResolverDomain(domain) ([]string, error) — resolve to IP list
  • ResolverDomain2Ip4(domain) (string, error) — resolve to first IPv4
  • NetRouteAdd/NetRouteDelete(iface, metric, cidr) — manage routes
  • RouteDefault/GetIfaceRouteDefault() — default route management
  • IpConfig/IpConfigAuto/IpFlush/IpDhcpRenew(...) — IP configuration
Discovery
  • NetInitDiscoveryServer(...) — register mDNS service
  • NetDiscoveryQuery(service, timeout, ifaces...) — mDNS browse
  • NetDiscoveryQueryCCC(service, ifaces...) — discover CCC devices
  • OnvifDiscovery(ifaces...) []CamerasInfo — ONVIF camera discovery
  • MacFromIP(ip, ifaces...) (string, error) — ARP lookup
Network Time
  • GetNetworkTime(ntpserver, port) (*time.Time, error) — NTP query
  • TimeGetUTCFromInternet() string — NTP then HTTP fallback
  • TimeUpdateFromInternet(tzone...) bool — sync system clock
REST API Builders
  • HABuildErrorCode(code, msg) HAErrorCode
  • HABuildErrorResponse(errors, messages) *HAErrorResponse
  • HABuildSuccessRespone(result, messages, resultInfo...) *HASuccessResponse
  • HABuildErrorResponseStr/HABuildSuccessResponeStr(...) — JSON string variants

Author

sonnt85thanhson.rf@gmail.com

License

MIT License - see LICENSE for details.

Documentation

Index

Constants

View Source
const (
	IfaceIname int = iota
	IfaceMacddr
	IfaceCidr
	IfaceIp4
	IfaceIp6
	IfaceMask
)
View Source
const (
	// Stolen from https://godoc.org/golang.org/x/net/internal/iana,
	// can't import "internal" packages
	ProtocolICMP = 1
)

Variables

This section is empty.

Functions

func DialExpec

func DialExpec(addr, expect string, timeouts ...time.Duration) bool

func GetDefaultIface

func GetDefaultIface() (string, error)

func GetFreePort

func GetFreePort(isUdp ...bool) (int, error)

func GetFreePorts

func GetFreePorts(count int, isUdp ...bool) ([]int, error)

func GetFreeTcpPort

func GetFreeTcpPort() (int, error)

func GetFreeTcpPorts

func GetFreeTcpPorts(count int) ([]int, error)

func GetFreeUdpPort

func GetFreeUdpPort() (int, error)

func GetFreeUdpPorts

func GetFreeUdpPorts(count int) ([]int, error)

func GetIfaceRouteDefault

func GetIfaceRouteDefault() (ifacename string)

func GetNetworkTime

func GetNetworkTime(ntpserver string, port int) (t *time.Time, err error)

GetNetworkTime retrieves the current UTC time from the remote NTP server It returns the go time.Time type of the current time in UTC.

func GetOutboundIP

func GetOutboundIP(iface ...string) (string, error)

func GetPublicIp

func GetPublicIp() string

func HABuildErrorResponseStr

func HABuildErrorResponseStr(errors []HAErrorCode, messages []HAMessages) (response string)

HABuildErrorResponseStr constructs an error response as a JSON string based on provided error codes and messages. Parameters:

errors: []HAErrorCode (type HAErrorCode struct {
  Code     int
  Messages string
}) - List of error codes and messages
messages: []HAMessages (map[string]interface{}) - List of messages

Returns:

response: string - Constructed error response as a JSON string

func HABuildSuccessResponeStr

func HABuildSuccessResponeStr(result HAResult, messages []HAMessages, result_info ...HAResultInfo) (response string)

HABuildSuccessResponeStr constructs a success response as a JSON string with the provided result, messages, and optional result information. Parameters:

result: HAResult (map[string]interface{})- Result of the operation
messages: []HAMessages (map[string]interface{}) - List of messages
result_info: ...HAResultInfo (map[string]interface{}) - Optional additional result information

Returns:

response: string - Constructed success response as a JSON string

func HttpClientFlush

func HttpClientFlush()

func HttpClientNewTransPort

func HttpClientNewTransPort() *http.Transport

func HttpClientReset

func HttpClientReset()

func IfaceGetAllName

func IfaceGetAllName(noLocalhosts ...bool) (ifaces []string)

func IfaceIsPluged

func IfaceIsPluged(ifacename string) bool

func IfaceListAll

func IfaceListAll()

func IfaceListHasInternet

func IfaceListHasInternet() (ifaces []string)

func IfaceRestart

func IfaceRestart(ifacname string) bool

func IpBetween

func IpBetween(from net.IP, to net.IP, test net.IP) bool

func IpConfig

func IpConfig(ipstr, maskstr, gwipstr string, ifaces ...string) error

func IpConfigAuto

func IpConfigAuto(ipcidr string, ifaces ...string) error

func IpDhcpRenew

func IpDhcpRenew(ifi string, timeouts ...time.Duration) error

func IpFlush

func IpFlush(ifi string) error

func IpGetDefault

func IpGetDefault(ipstr string) (mask, gw string, err error)

func IpInc

func IpInc(ip net.IP)

func IpIsPrivate

func IpIsPrivate(ip string) bool

func IpParserCIDR

func IpParserCIDR(cidr string) (maskip, defaultgateway string, err error)

func IsOnline

func IsOnline(times, intervalsecs int) bool

func IsPortAvailable

func IsPortAvailable(ip string, port int, timeouts ...time.Duration) bool

func IsPortOpen

func IsPortOpen(addr string, port int, proto string, timeouts ...time.Duration) bool

func IsPortOpen1

func IsPortOpen1(addr string, port int, proto string, timeouts ...time.Duration) bool

func IsPortTcpAvailable

func IsPortTcpAvailable(ip string, port int, timeouts ...time.Duration) bool

func IsPortTcpUsed

func IsPortTcpUsed(ip string, port int, timeouts ...time.Duration) bool

func IsPortUdpAvailable

func IsPortUdpAvailable(ip string, port int, timeouts ...time.Duration) bool

func IsPortUdpUsed

func IsPortUdpUsed(ip string, port int, timeouts ...time.Duration) bool

func IsPortUsed

func IsPortUsed(ip string, port int, timeouts ...time.Duration) bool

func IsPublicIP

func IsPublicIP(IP net.IP) bool

func IsSsh

func IsSsh(addr string, timeouts ...time.Duration) bool

func IsVnc

func IsVnc(addr string, timeouts ...time.Duration) bool

func MacFromIP

func MacFromIP(ip2check string, ifaceFlags ...string) (info string, err error)

func NMConnectWifi

func NMConnectWifi(ifacename, ssid, password string) error

func NMCreateHostPost

func NMCreateHostPost(ifacename, conname, ssid, password string) error

func NetCheckConectionToServer

func NetCheckConectionToServer(domain string, ifacenames ...string) error

func NetDiscoveryConfigPort

func NetDiscoveryConfigPort(port int)

func NetDiscoveryQueryServiceEntry

func NetDiscoveryQueryServiceEntry(serviceName, domain string, timeout time.Duration, ifaceNames ...string) []*mdns.ServiceEntry

func NetGetCIDR

func NetGetCIDR(iface ...string) (string, error)

func NetGetDefaultGatewayOfIface

func NetGetDefaultGatewayOfIface(iface ...string) (string, error)

func NetGetGatewayOfInterface

func NetGetGatewayOfInterface(ifaceCheck string) (string, error)

func NetGetInameByIP

func NetGetInameByIP(ip string) (i string, err error)

func NetGetInterfaceInfo

func NetGetInterfaceInfo(infotype int, ifaces ...string) (info string, err error)

infotype 0 interface name, 1 macaddr, 2 cidr, >2 lanip]

func NetGetInterfaceIpv4Addr

func NetGetInterfaceIpv4Addr(interfaceName string) (addr string, err error)

func NetGetMac

func NetGetMac(iface ...string) (macadd string, err error)

func NetGetMacBytesInterFace

func NetGetMacBytesInterFace(interfaceName string) (macadd []byte, err error)

func NetGetMacInterFace

func NetGetMacInterFace(interfaceName string) (macadd string, err error)

func NetGetMacs

func NetGetMacs(iface ...string) ([]string, error)

func NetGetMask

func NetGetMask(iface ...string) (string, error)

func NetGetMetricOfInterface

func NetGetMetricOfInterface(ifaceCheck string, cirdOrIp string) (int, error)

func NetGetStaticLoopbackName

func NetGetStaticLoopbackName() (retstr string)

func NetGetStaticMac

func NetGetStaticMac() string

func NetIfaceHasIpv4

func NetIfaceHasIpv4(interfaceName string) bool

func NetInitDiscoveryServer

func NetInitDiscoveryServer(ipService interface{}, serviceport interface{}, id, serviceName string, info interface{}, ifaceName ...interface{}) (s *mdns.Server, err error)

ipService: net.IP, *net.IP, []net.IP, *[]net.IP, string, *string, []string, *[]string => *[]net.IP serviceport: int, *int => *int info: string, []string, *[]string => *[]string ifaceName: string, net.Interface, *net.Interface => *net.Interface

func NetInterfaceIsUp

func NetInterfaceIsUp(ifaceName string) (bool, error)

func NetIsIpv4

func NetIsIpv4(ip net.IP) bool

func NetIsOnline

func NetIsOnline(times, intervalsecs int, ifacenames ...string) bool

func NetIsOnlineOld

func NetIsOnlineOld(times, intervalsecs int, ifacenames ...string) bool

func NetIsOnlinePing

func NetIsOnlinePing(times, intervalsecs int, ifacenames ...string) bool

func NetIsOnlinePingExternal

func NetIsOnlinePingExternal(times, intervalsecs int, ifacenames ...string) bool

func NetIsOnlineTcp

func NetIsOnlineTcp(times, intervalsecs int, ifacenames ...string) bool

func NetRouteAdd

func NetRouteAdd(iface string, metric int, cirdOrIp string) (cmd2run string, err error)

func NetRouteAddTemporary

func NetRouteAddTemporary(iface string, metric int, cirdOrIp string) (err error)

func NetRouteDelete

func NetRouteDelete(iface string, metric int, cirdOrIp string) (cmd2run string, err error)

func NetTCPClientSend

func NetTCPClientSend(servAddr string, dataSend []byte, timeouts ...time.Duration) (retbytes []byte, err error)

func NetWaitServerIsOnline

func NetWaitServerIsOnline(domain string, timeout time.Duration, ifacenames ...string) error

func OnvifSendProbe

func OnvifSendProbe(ifaceName ...string) (devices []string)

func Ping

func Ping(addr, iface string, timeouts ...time.Duration) (*net.IPAddr, time.Duration, error)

func PingExternal

func PingExternal(domain, ifacename string, timeout time.Duration) error

func ResolverDomain

func ResolverDomain(domain string, debugflag ...bool) (addrs []string, err error)

func ResolverDomain2Ip4

func ResolverDomain2Ip4(domain string, debugflag ...bool) (addr string, err error)

func ResolverDomainOld

func ResolverDomainOld(domain string, debugflag ...bool) (addrs []string, err error)

func RouteDefault

func RouteDefault(ifacename string, metrics ...int) (err error)

func RouteTem

func RouteTem(ifacename string, metrics ...int) (err error)

func ServerIsLive

func ServerIsLive(domain string, ifacenames ...string) bool

func TimeGetUTCFromInternet

func TimeGetUTCFromInternet() (t string)

func TimeGetUTCFromhttp

func TimeGetUTCFromhttp() (gmtteme string)

func TimeUpdateFromInternet

func TimeUpdateFromInternet(tzone ...string) bool

func TimeZoneGet

func TimeZoneGet() (tz string)

Types

type CamerasInfo

type CamerasInfo struct {
	From             string    `json:"from"`
	IP               string    `json:"ip"`
	Name             string    `json:"name"`
	XADDR            string    `json:"xaddr"`
	UUID             string    `json:"uuid"`
	Hardware         string    `json:"hardware"`
	Location         string    `json:"location"`
	FirmwareVersion  string    `json:"firmware version"`
	LastConnectError time.Time `json:"last_error_time"`
}

func OnvifDiscovery

func OnvifDiscovery(ifaceName ...string) []CamerasInfo

type DeviceCCCInfo

type DeviceCCCInfo struct {
	From          string    `json:"from"`
	IP            string    `json:"ip"`
	Port          int       `json:"port"`
	Serial_number string    `json:"serial_number"`
	Device_id     string    `json:"device_id"`
	Extra         []string  `json:"more"`
	LastDiscovery time.Time `json:"-"`
	Version       string    `json:"Version"`
}

func NetDiscoveryQueryCCC

func NetDiscoveryQueryCCC(servicename string, ifaceName ...string) (deviceList []DeviceCCCInfo)

type DiscoveryInfo

type DiscoveryInfo struct {
	Name string
	Host string
	Ip4  string
	Port int
	Info []string
}

func NetDiscoveryQuery

func NetDiscoveryQuery(serviceName string, timeout time.Duration, ifaceNames ...string) []*DiscoveryInfo

type HA

type HA map[string]interface{}

HA is a type alias representing a map with string keys and interface{} values.

type HAErrorCode

type HAErrorCode struct {
	Code     int
	Messages string
}

HAErrorCode represents an error code along with a message.

func HABuildErrorCode

func HABuildErrorCode(code int, msg string) HAErrorCode

type HAErrorResponse

type HAErrorResponse struct {
	HAResponseCommon
}

HAErrorResponse represents an error response containing common response fields.

func HABuildErrorResponse

func HABuildErrorResponse(errors []HAErrorCode, messages []HAMessages) (response *HAErrorResponse)

HABuildErrorResponse constructs an error response based on provided error codes and messages. Parameters:

struct HAErrorCode { Code int; Messages string }
errors: []HAErrorCode - List of error codes and messages

messages: []HAMessages (map[string]interface{}) - List of messages

Returns:

response: *HAErrorResponse - Constructed error response

type HAMessages

type HAMessages map[string]interface{}

HAMessages is a type alias representing a map with string keys and interface{} values, typically used for representing messages in the response.

type HAResponseCommon

type HAResponseCommon struct {
	Result   HAResult      `json:"result"`   // Result of the operation, nil for error
	Success  bool          `json:"success"`  // Indicates success or failure (false/true)
	Errors   []HAErrorCode `json:"errors"`   // List of error codes and messages
	Messages []HAMessages  `json:"messages"` // List of messages
}

HAResponseCommon is a common structure for both error and success responses.

type HAResult

type HAResult map[string]interface{}

HAResult is a type alias representing a map with string keys and interface{} values, typically used for representing the result of an operation in the response.

type HAResultInfo

type HAResultInfo map[string]interface{}

HAResultInfo is a type alias representing a map with string keys and interface{} values, often used for representing additional information about the result.

type HASuccessResponse

type HASuccessResponse struct {
	HAResponseCommon
	Result_info HAResultInfo `json:"result_info"` // Additional result information
}

HASuccessResponse represents a success response containing common response fields along with additional result information.

func HABuildSuccessRespone

func HABuildSuccessRespone(result HAResult, messages []HAMessages, result_info ...HAResultInfo) (response *HASuccessResponse)

HABuildSuccessRespone constructs a success response with the provided result, messages, and optional result information. Parameters:

result: HAResult (map[string]interface{})- Result of the operation
messages: []HAMessages (map[string]interface{}) - List of messages
result_info: ...HAResultInfo (map[string]interface{}) - Optional additional result information

Returns:

response: *HASuccessResponse - Constructed success response

Jump to

Keyboard shortcuts

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