Created
August 31, 2016 04:47
-
-
Save hayajo/9e0d8adb8dce36ecb1abf56fc2d372ee to your computer and use it in GitHub Desktop.
近いホストを探す
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
雑実装