Skip to content

Instantly share code, notes, and snippets.

@jdhenke
Last active Nov 14, 2015
Embed
What would you like to do?
package main
import (
"flag"
"log"
"net"
)
const (
defaultAddr = ":1234"
defaultNumTries = 4
)
var (
addr string
numTries int
)
func main() {
// use flags
flag.StringVar(&addr, "addr", defaultAddr, "address on which to listen")
flag.IntVar(&numTries, "n", defaultNumTries, "number of consecutive tries")
flag.Parse()
log.Printf("Using address=`%v`\n", addr)
log.Printf("Will try %v times\n", numTries)
// listen and close numTries times binding to addr
for i := 0; i < numTries; i++ {
listenAndClose(i)
}
// sweet, no issues.
log.Printf("PASS\n")
}
// listenAndClose creates a tcp listener on addr and closes it, logging its
// actions to and exiting the program in the event of an error.
func listenAndClose(i int) {
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("creating ln %v failed: %v\n", i, err)
}
log.Printf("%3d: listener created on %v\n", i, ln.Addr())
if err := ln.Close(); err != nil {
log.Fatalf("closing ln %v failed: %v\n", i, err)
}
log.Printf("%3d: listener closed\n", i)
}
@jdhenke
Copy link
Author

jdhenke commented Nov 14, 2015

(master=)$ go version
go version go1.5 darwin/amd64
(master=)$ go run main.go
2015/11/14 13:32:41 Using address=`:1234`
2015/11/14 13:32:41 Will try 4 times
2015/11/14 13:32:41   0: listener created on [::]:1234
2015/11/14 13:32:41   0: listener closed
2015/11/14 13:32:41   1: listener created on [::]:1234
2015/11/14 13:32:41   1: listener closed
2015/11/14 13:32:41   2: listener created on [::]:1234
2015/11/14 13:32:41   2: listener closed
2015/11/14 13:32:41   3: listener created on [::]:1234
2015/11/14 13:32:41   3: listener closed
2015/11/14 13:32:41 PASS
(master=)$ go run main.go -addr=""
2015/11/14 13:32:46 Using address=``
2015/11/14 13:32:46 Will try 4 times
2015/11/14 13:32:46   0: listener created on [::]:65349
2015/11/14 13:32:46   0: listener closed
2015/11/14 13:32:46   1: listener created on [::]:65350
2015/11/14 13:32:46   1: listener closed
2015/11/14 13:32:46   2: listener created on [::]:65351
2015/11/14 13:32:46   2: listener closed
2015/11/14 13:32:46   3: listener created on [::]:65352
2015/11/14 13:32:46   3: listener closed
2015/11/14 13:32:46 PASS

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment