Mastering Go Socket Programming: From TCP/UDP to HTTP Clients

This article explains Go’s socket programming model, covering the classic five‑step workflow, the versatile net.Dial function, and practical code examples for ICMP, TCP, and HTTP client operations, helping developers build networked applications efficiently.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Go Socket Programming: From TCP/UDP to HTTP Clients

Socket Programming

Traditional socket programming follows five steps: create a socket with socket(), bind it with bind(), listen (or connect) using listen() or connect(), accept connections with accept(), and finally send or receive data using send() and receive(). Go’s standard library abstracts these steps into the single net.Dial() call, handling various protocols automatically.

Dial() Function

The signature of Dial is: func Dial(net, addr string) (Conn, error) The net argument specifies the protocol name (e.g., "tcp", "udp", "ip4:icmp") and addr provides the IP address or hostname, optionally followed by a port. If the connection succeeds, a Conn object is returned; otherwise an error is returned.

Examples:

conn, err := net.Dial("tcp", "192.168.0.10:2100")
conn, err := net.Dial("udp", "192.168.0.12:975")
conn, err := net.Dial("ip4:icmp", "www.baidu.com")
conn, err := net.Dial("ip4:1", "10.0.0.3")

Supported protocols include "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip", "ip4", and "ip6". After a successful connection, data can be sent with Write() and received with Read().

ICMP Example

The following program sends an ICMP echo request to a host and checks the identifier and sequence fields in the reply.

package main
import (
    "net"
    "os"
    "bytes"
    "fmt"
)

func main() {
    if len(os.Args) != 2 {
        fmt.Println("Usage:", os.Args[0], "host")
        os.Exit(1)
    }
    service := os.Args[1]
    conn, err := net.Dial("ip4:icmp", service)
    checkError(err)

    var msg [512]byte
    msg[0] = 8
    msg[1] = 0
    // ... (initialize rest of ICMP header)
    // Compute checksum, send, receive, and verify response
    // (full code omitted for brevity)
}
... (additional helper functions) ...

Running the program prints “Got response”, “Identifier matches”, and “Sequence matches” when the reply is valid.

TCP Example

This example establishes a TCP connection, sends a simple HTTP HEAD request, and prints the server’s response.

package main
import (
    "net"
    "os"
    "bytes"
    "fmt"
)

func main() {
    if len(os.Args) != 2 {
        fmt.Fprintf(os.Stderr, "Usage: %s host:port
", os.Args[0])
        os.Exit(1)
    }
    service := os.Args[1]
    conn, err := net.Dial("tcp", service)
    checkError(err)
    _, err = conn.Write([]byte("HEAD / HTTP/1.0

"))
    checkError(err)
    result, err := readFully(conn)
    checkError(err)
    fmt.Println(string(result))
}
... (helper functions) ...

When run against a host, it outputs the HTTP status line and headers, e.g., “HTTP/1.1 301 Moved Permanently”.

HTTP Programming

Go’s net/http package provides built‑in support for HTTP clients and servers. The Client type offers methods such as Get, Post, PostForm, Head, and Do for various request patterns.

Basic HTTP Methods

Example of a simple GET request:

resp, err := http.Get("http://example.com/")
if err != nil {
    // handle error
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)

POSTing data, submitting forms, and customizing requests with custom headers can be done using http.Post, http.PostForm, or by constructing a http.Request and calling client.Do(req).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GoTCPHTTPCode Examplessocket programmingUDPICMP
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.