Skip to main content

Overview

The Connections family of functions retrieves information about active network connections on the system. These functions allow filtering by connection type, process ID, and can limit the number of results.

Functions

Basic Connection Functions

func Connections(kind string) ([]ConnectionStat, error)
func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error)
Returns a list of all network connections matching the specified type.

Process-Specific Connections

func ConnectionsPid(kind string, pid int32) ([]ConnectionStat, error)
func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error)
Returns connections for a specific process ID.

Limited Result Functions

func ConnectionsMax(kind string, maxConn int) ([]ConnectionStat, error)
func ConnectionsMaxWithContext(ctx context.Context, kind string, maxConn int) ([]ConnectionStat, error)

func ConnectionsPidMax(kind string, pid int32, maxConn int) ([]ConnectionStat, error)
func ConnectionsPidMaxWithContext(ctx context.Context, kind string, pid int32, maxConn int) ([]ConnectionStat, error)
Returns at most maxConn connections per process.

Performance-Optimized Variants

func ConnectionsWithoutUids(kind string) ([]ConnectionStat, error)
func ConnectionsWithoutUidsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error)

func ConnectionsPidWithoutUids(kind string, pid int32) ([]ConnectionStat, error)
func ConnectionsPidWithoutUidsWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error)

func ConnectionsPidMaxWithoutUids(kind string, pid int32, maxConn int) ([]ConnectionStat, error)
func ConnectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, maxConn int) ([]ConnectionStat, error)
The WithoutUids variants omit the Uids field for performance optimization. These functions are reliant on implementation details and may be altered or removed in future versions.

Parameters

kind
string
required
Connection type filter. Supported values:
  • "tcp" - TCP connections only
  • "tcp4" - TCP IPv4 connections
  • "tcp6" - TCP IPv6 connections
  • "udp" - UDP connections only
  • "udp4" - UDP IPv4 connections
  • "udp6" - UDP IPv6 connections
  • "unix" - Unix domain sockets
  • "inet" - All internet connections (tcp + udp)
  • "inet4" - All IPv4 connections
  • "inet6" - All IPv6 connections
  • "all" - All connection types
pid
int32
Process ID to filter connections for
maxConn
int
Maximum number of connections to return per process
ctx
context.Context
Context for cancellation and timeout control

ConnectionStat Structure

The ConnectionStat struct represents a single network connection.
type ConnectionStat struct {
    Fd     uint32  // File descriptor
    Family uint32  // Address family (AF_INET, AF_INET6, etc.)
    Type   uint32  // Socket type (SOCK_STREAM, SOCK_DGRAM, etc.)
    Laddr  Addr    // Local address
    Raddr  Addr    // Remote address
    Status string  // Connection status
    Uids   []int32 // User IDs associated with the connection
    Pid    int32   // Process ID
}

Fields

Fd
uint32
File descriptor number for the socket.
Family
uint32
Address family constant (e.g., AF_INET for IPv4, AF_INET6 for IPv6).
Type
uint32
Socket type constant (e.g., SOCK_STREAM for TCP, SOCK_DGRAM for UDP).
Laddr
Addr
Local address and port of the connection.
Raddr
Addr
Remote address and port of the connection.
Status
string
Connection status string (e.g., “ESTABLISHED”, “LISTEN”, “TIME_WAIT”, “CLOSE_WAIT”).
Uids
[]int32
Array of user IDs associated with this connection. Empty in WithoutUids variants.
Pid
int32
Process ID that owns this connection.

Addr Structure

The Addr struct represents a network address and port.
type Addr struct {
    IP   string // IP address
    Port uint32 // Port number
}
IP
string
IP address as a string (e.g., “192.168.1.100”, “::1”).
Port
uint32
Port number (0-65535).

Usage Examples

Get All TCP Connections

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/net"
)

func main() {
    conns, err := net.Connections("tcp")
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Total TCP connections: %d\n\n", len(conns))
    
    for _, conn := range conns {
        fmt.Printf("PID: %d, Status: %s\n", conn.Pid, conn.Status)
        fmt.Printf("  Local:  %s:%d\n", conn.Laddr.IP, conn.Laddr.Port)
        fmt.Printf("  Remote: %s:%d\n\n", conn.Raddr.IP, conn.Raddr.Port)
    }
}

Filter by Connection Status

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/net"
)

func main() {
    conns, err := net.Connections("tcp")
    if err != nil {
        panic(err)
    }
    
    established := 0
    listening := 0
    
    for _, conn := range conns {
        switch conn.Status {
        case "ESTABLISHED":
            established++
        case "LISTEN":
            listening++
        }
    }
    
    fmt.Printf("Established: %d\n", established)
    fmt.Printf("Listening: %d\n", listening)
}

Get Connections for Specific Process

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/net"
)

func main() {
    pid := int32(1234) // Replace with actual PID
    
    conns, err := net.ConnectionsPid("all", pid)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Connections for PID %d: %d\n", pid, len(conns))
    
    for _, conn := range conns {
        fmt.Printf("  %s:%d -> %s:%d [%s]\n",
            conn.Laddr.IP, conn.Laddr.Port,
            conn.Raddr.IP, conn.Raddr.Port,
            conn.Status)
    }
}

Monitor Listening Ports

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/net"
)

func main() {
    conns, err := net.Connections("inet")
    if err != nil {
        panic(err)
    }
    
    fmt.Println("Listening ports:")
    
    for _, conn := range conns {
        if conn.Status == "LISTEN" {
            fmt.Printf("  Port %d (PID: %d)\n", conn.Laddr.Port, conn.Pid)
        }
    }
}

Using Context with Timeout

package main

import (
    "context"
    "fmt"
    "time"
    "github.com/shirou/gopsutil/v4/net"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    conns, err := net.ConnectionsWithContext(ctx, "tcp")
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Found %d TCP connections\n", len(conns))
}

Limit Number of Results

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/v4/net"
)

func main() {
    // Get at most 10 connections per process
    conns, err := net.ConnectionsMax("tcp", 10)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Got %d connections (max 10 per process)\n", len(conns))
}

Connection Status Values

Common TCP connection status values:
  • ESTABLISHED - Connection is established and active
  • SYN_SENT - Attempting to establish connection
  • SYN_RECV - Received connection request
  • FIN_WAIT1 - Connection is closing
  • FIN_WAIT2 - Connection closed, waiting for remote shutdown
  • TIME_WAIT - Connection closed, waiting for retransmissions
  • CLOSE - Connection is closed
  • CLOSE_WAIT - Remote end has shut down, waiting for local close
  • LAST_ACK - Waiting for final acknowledgment
  • LISTEN - Listening for incoming connections
  • CLOSING - Both sides closing simultaneously
  • NONE - No status (typically UDP)

Platform Support

Connection monitoring is supported on:
  • Linux
  • macOS
  • Windows
  • FreeBSD
  • OpenBSD
  • Solaris
Some fields may have limited availability on certain platforms.

Performance Considerations

For better performance when you don’t need UID information, use the WithoutUids variants. These skip UID resolution which can be expensive on systems with many connections.

See Also

Build docs developers (and LLMs) love