Skip to content

Commit

Permalink
example: add tcp port scanner
Browse files Browse the repository at this point in the history
  • Loading branch information
WangYihang committed May 3, 2024
1 parent 8b7770c commit 3548d1b
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
34 changes: 34 additions & 0 deletions examples/tcp-port-scanner/main.go
Original file line number Diff line number Diff line change
@@ -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()
}
22 changes: 22 additions & 0 deletions examples/tcp-port-scanner/status.go
Original file line number Diff line number Diff line change
@@ -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
}
31 changes: 31 additions & 0 deletions examples/tcp-port-scanner/task.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 3548d1b

Please sign in to comment.