# README
getport
A simple Go module that provides methods for find an open port on the local system. A comprehensive set of methods for getting open TCP or UDP ports on either the IPv4 or IPv6 network stacks are provided.
Install
$ go get github.com/jsumners/go-getport
Example
The following example shows a simple TCP server that will write hello world
and close the connection when a connection is made, e.g. via netcat
(nc 127.0.0.1 <discovered-port>
).
package main
import (
getport "github.com/jsumners/go-getport"
"net"
)
func main() {
// Get an open TCP port on the localhost address.
// `getport.GetTcpPort()` would instead listen on all addresses with
// a common free port.
portResult, getPortError := getport.GetTcpPortForAddress("127.0.0.1")
if getPortError != nil {
panic(getPortError)
}
listenAddress := getport.PortResultToAddress(portResult)
listener, listenError := net.Listen("tcp", listenAddress)
if listenError != nil {
panic(listenError)
}
println("listening on: ", listenAddress)
defer listener.Close()
connection, connError := listener.Accept()
if connError != nil {
panic(connError)
}
connection.Write([]byte("hello world"))
connection.Close()
}
# Functions
GetPort finds an open port for a given [Protocol] and address and returns that port number.
GetTcp4Port gets a port for some random available address using TCP4.
GetTcp4PortForAddress gets a TCP4 port for the given address.
GetTcp6Port gets a port for some random available address using TCP6.
GetTcp6PortForAddress gets a TCP6 port for the given address.
GetTcpPort gets a port for some random available address using either TCP4 or TCP6.
GetTcpPortForAddress gets either a TCP4 or TCP6 port for the given address.
GetUdp4Port gets a port for some random available address using UDP4.
GetUdp4PortForAddress gets a UDP4 port for the given address.
GetUdp6Port gets a port for some random available address using UDP6.
GetUdp6PortForAddress gets a UDP6 port for the given address.
GetUdpPort gets a port for some random available address using either UDP4 or UDP6.
GetUdpPortForAddress gets either a UDP4 or UDP6 port for the given address.
PortResultToAddress converts a [PortResult] into a traditional host:port string usable by [net.Listen] or [net.ListenPacket].
# Constants
TCP indicates to let the OS decide between IPv4 and IPv6 when finding an open TCP based port.
TCP4 indicates to find an open IPv4 port.
TCP6 indicates to find an open IPv6 port.
UDP indicates to let the OS decide between IPv4 and IPv6 when finding an open UDP based port.
UDP4 indicates to find an open IPv4 port.
UDP6 indicates to find an open IPv6 port.
# Structs
PortResult represents the result of [GetPort].
# Type aliases
Protocol indicates the communication protocol (tcp or udp) and network stack (IPv4, IPv6, or OS choice) to target when finding an available port.