Last active
November 12, 2018 05:55
-
-
Save ik5/9e37ff476d243a160cfa069cfb90fb24 to your computer and use it in GitHub Desktop.
Simple port scanner example written in go
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" | |
"strings" | |
"time" | |
) | |
const ( | |
errUnknown = "Unknown error" | |
connTimeout = "closed" | |
connFiltered = "filtered" | |
resolveError = "Resolve error" | |
lookupError = "Lookup error" | |
connSuccess = "open" | |
) | |
func tcpConnect(address string, port int, timeout time.Duration) (string, error) { | |
ipList, err := net.LookupHost(address) | |
if err != nil { | |
return lookupError, err | |
} | |
if len(ipList) == 0 { | |
return resolveError, fmt.Errorf("Unable to resolve %s", address) | |
} | |
connAddr := fmt.Sprintf("%s:%d", ipList[0], port) | |
conn, err := net.DialTimeout("tcp", connAddr, timeout) | |
if err != nil { | |
sErr := err.Error() | |
if strings.HasSuffix(sErr, "connection refused") { | |
return connFiltered, err | |
} | |
if strings.HasSuffix(sErr, "i/o timeout") { | |
return connTimeout, err | |
} | |
return errUnknown, err | |
} | |
defer conn.Close() | |
return connSuccess, nil | |
} | |
func main() { | |
addr := "google.com" | |
port := 443 | |
status, err := tcpConnect(addr, port, time.Duration(3)*time.Second) | |
fmt.Printf("%s:%d - ", addr, port) | |
if status == errUnknown { | |
fmt.Println(err) | |
} else { | |
fmt.Println(status) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment