Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "net"
- "time"
- "fmt"
- )
- func main() {
- // this is an "array" or "slice" (a collection of something)
- // the []string defines how it is to be stored, string is "text" where as an "int" or "integer" can only be a number
- // putting [] infront of a type (such as string or int) makes it a collection
- // in bash this is probably written something like Array("address1", "address2")
- hosts := []string{"10.0.0.200", "10.0.0.84", "google.com", "telstra.com", "syscad.net"}
- // this is a "for loop", it loops through a collection (array or slice)
- // in this example it will go through each item in hosts
- // `range hosts` // loop through hosts from start to end
- // `host` // this is how you 'access' each item that's benig looped over
- // host will equal: "10.0.0.200" then "10.0.0.84" then "google.com" then "telstra.com" then "syscad.net" then stop
- for _, host := range hosts {
- // here I'm running a function, this is similar to running any command in bash with parameters
- // such as `ping 8.8.8.8` where 'ping'(checkIp) is the function name and '8.8.8.8'(host) is the parameter
- // I have an extra parameter here for port so you specifically target a service - 80 is for a web service,
- // but you could also target a printing port service
- checkIp(host, 80)
- }
- }
- func checkIp(host string, port int) {
- // fmt.Sprintf is a text formatting package
- // here I'm setting `address` to address:port ie google.com:80
- address := fmt.Sprintf("%s:%d", host, port)
- // this is essentially the same as you netcat command
- // it attempts to connect to the address over tcp with a 5 second timeout (so it doesn't hang forever)
- conn, err := net.DialTimeout("tcp", address, time.Second * 5)
- // don't worry about this it's just cleaning up the connection as it will leave a network socket open if you don't
- if conn != nil {
- defer conn.Close()
- }
- // if there was an error with connecting (ie host is down) print out that the connection had failed
- if err != nil {
- fmt.Printf("%s failed\n", address)
- } else {
- // otherwise print out that it was a success
- fmt.Printf("%s success\n", address)
- }
- }
- // the output of this program is
- // 10.0.0.200:80 success
- // 10.0.0.84:80 failed
- // google.com:80 success
- // telstra.com:80 success
- // syscad.net:80 success
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement