conn, err := net.Dial("tcp", "example.com:80") if err != nil { log.Fatalf("Error connecting: %v", err) } defer conn.Close() localAddr := conn.LocalAddr() fmt.Println("Local address:", localAddr)
conn, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Fatalf("Error listening: %v", err) } defer conn.Close() localAddr := conn.Addr().(*net.TCPAddr) fmt.Println("Local IP:", localAddr.IP) fmt.Println("Local port:", localAddr.Port)In this example, we create a new TCP listener on "localhost" on port 8080 using the `net.Listen()` method. We then defer the `Close()` method to ensure that the listener is closed when we are finished with it. Finally, we use the `Addr()` method to get the address of the listener and convert it to a `net.TCPAddr` type. We can then access the IP address and port of the local network address and print them to the console.