Test TCP and UDP over loopback
Test TCP and UDP over loopback
Loopback tests exercise actual OS sockets without external services. Bind only to 127.0.0.1 and port 0; retrieve the selected address rather than hardcoding a port. Set deadlines and close every socket. TCP is a stream; UDP preserves individual datagram boundaries but may lose packets. Local success does not establish internet delivery, latency or ordering guarantees.
package main
import ( "fmt" "io" "net" "time")
func check(e error) { if e != nil { panic(e) }}func main() { l, e := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) check(e) defer l.Close() check(l.SetDeadline(time.Now().Add(2 * time.Second))) c, e := net.DialTimeout("tcp4", l.Addr().String(), time.Second) check(e) defer c.Close() s, e := l.AcceptTCP() check(e) defer s.Close() check(c.SetDeadline(time.Now().Add(time.Second))) check(s.SetDeadline(time.Now().Add(time.Second))) _, e = c.Write([]byte("ping")) check(e) p := make([]byte, 4) _, e = io.ReadFull(s, p) check(e) _, e = s.Write([]byte("pong")) check(e) _, e = io.ReadFull(c, p) check(e) fmt.Println(string(p))}This fixture checks a request and response with a known four-byte protocol. A test failure may reflect a blocked socket or a deadline, not necessarily incorrect application logic. Use net.Pipe for logic-only tests if socket access is restricted; do not treat it as a kernel TCP test.
Expected output:
pongReceive one UDP datagram at a time
package main
import ( "fmt" "net" "time")
func check(e error) { if e != nil { panic(e) }}func main() { s, e := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) check(e) defer s.Close() c, e := net.DialUDP("udp4", nil, s.LocalAddr().(*net.UDPAddr)) check(e) defer c.Close() check(c.SetDeadline(time.Now().Add(time.Second))) check(s.SetDeadline(time.Now().Add(time.Second))) _, e = c.Write([]byte("hi")) check(e) p := make([]byte, 32) n, peer, e := s.ReadFromUDP(p) check(e) fmt.Println(string(p[:n]), peer.IP.IsLoopback())}ReadFromUDP returns the received byte count and sender address. Use a sufficiently large buffer for your protocol; if it is too small, the excess datagram bytes are not available in a later read. For this test use a small known datagram and no external network. A connected UDP socket specifies a peer; it does not perform a TCP-like handshake.
Expected output:
hi trueTry it locally
Send a UDP datagram OK to a local OS-selected port and print the payload length and text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Networking 06: Test TCP and UDP over loopback
Check the lesson objective before moving on.
Why bind to port 0 in a test?
What happens to excess UDP datagram bytes when the receive buffer is too small?