diff --git a/examples/tcp-port-scanner/main.go b/examples/tcp-port-scanner/main.go new file mode 100644 index 0000000..a6161f9 --- /dev/null +++ b/examples/tcp-port-scanner/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "github.com/WangYihang/gojob" +) + +func main() { + var commonPorts = []uint16{ + 21, 22, 23, 25, 53, 80, 110, 135, 139, 143, 443, 445, 993, 995, + 1723, 3306, 3389, 5900, 8080, + } + var ips = []string{ + "192.168.200.1", + "192.168.200.254", + } + scheduler := gojob.New( + gojob.WithNumWorkers(8), + gojob.WithMaxRetries(4), + gojob.WithMaxRuntimePerTaskSeconds(16), + gojob.WithNumShards(1), + gojob.WithShard(0), + gojob.WithTotalTasks(int64(len(ips)*len(commonPorts))), + gojob.WithStatusFilePath("status.json"), + gojob.WithResultFilePath("result.json"), + gojob.WithMetadataFilePath("metadata.json"), + ). + Start() + for _, ip := range ips { + for _, port := range commonPorts { + scheduler.Submit(New(ip, port)) + } + } + scheduler.Wait() +} diff --git a/examples/tcp-port-scanner/status.go b/examples/tcp-port-scanner/status.go new file mode 100644 index 0000000..a8527c6 --- /dev/null +++ b/examples/tcp-port-scanner/status.go @@ -0,0 +1,22 @@ +package main + +type Status uint8 + +const ( + Unknown Status = iota + Open + Closed +) + +func (s Status) String() string { + statuses := map[Status]string{ + Unknown: "Undefined", + Open: "Open", + Closed: "Closed", + } + return statuses[s] +} + +func (s Status) MarshalJSON() ([]byte, error) { + return []byte(`"` + s.String() + `"`), nil +} diff --git a/examples/tcp-port-scanner/task.go b/examples/tcp-port-scanner/task.go new file mode 100644 index 0000000..ff5d3ce --- /dev/null +++ b/examples/tcp-port-scanner/task.go @@ -0,0 +1,31 @@ +package main + +import "net" + +type MyTask struct { + IP string `json:"ip"` + Port uint16 `json:"port"` + Status Status `json:"status"` +} + +func New(ip string, port uint16) *MyTask { + return &MyTask{ + IP: ip, + Port: port, + Status: Unknown, + } +} + +func (t *MyTask) Do() error { + conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{ + IP: net.ParseIP(t.IP), + Port: int(t.Port), + }) + if err != nil { + t.Status = Closed + return nil + } + defer conn.Close() + t.Status = Open + return nil +}