Skip to content

Instantly share code, notes, and snippets.

@hayajo
Created August 31, 2016 04:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hayajo/9e0d8adb8dce36ecb1abf56fc2d372ee to your computer and use it in GitHub Desktop.
Save hayajo/9e0d8adb8dce36ecb1abf56fc2d372ee to your computer and use it in GitHub Desktop.
近いホストを探す
package main
import (
"fmt"
"net"
"os"
"time"
)
func main() {
responses := make(chan string, len(os.Args[1:]))
start := make(chan struct{})
for _, hostname := range os.Args[1:] {
go func(hostname string) {
<-start // startがcloseするまでブロック
responses <- request(hostname)
}(hostname)
}
close(start) // すべてのゴルーチンを生成してから処理を一斉に開始する
for i := 0; i < cap(responses); i++ {
hostname := <-responses
if hostname != "" {
fmt.Printf("most recent host is %s\n", hostname)
close(responses)
break
}
}
}
func request(hostname string) (response string) {
start := time.Now()
// conn, err := net.Dial("ip4:icmp", hostname) // 一般ユーザーだとRAWパケットを扱えない(CAP_NET_RAW)のでicmpはやめる
conn, err := net.Dial("tcp", fmt.Sprintf("%s:80", hostname)) // ホストのポート80にTCP接続
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: connection failed %s: %v\n", hostname, err)
return
}
defer conn.Close()
fmt.Printf("%.2fs %s\n", time.Since(start).Seconds(), hostname)
response = hostname
return
}
@hayajo
Copy link
Author

hayajo commented Aug 31, 2016

雑実装

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