-
Notifications
You must be signed in to change notification settings - Fork 0
/
filterips.go
91 lines (79 loc) · 1.75 KB
/
filterips.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bufio"
"flag"
"fmt"
"net"
"os"
"regexp"
"strconv"
)
func main() {
includePorts := flag.Bool("ports", false, "include ports in the output")
flag.Parse()
ipv4Regex := regexp.MustCompile(`(\b\d{1,3}(\.\d{1,3}){3}\b)(:\d+)?`)
ipv6Regex := regexp.MustCompile(`(\b[0-9a-fA-F:]+\b)(:\d+)?`)
scanner := bufio.NewScanner(os.Stdin)
lines := make(chan string)
results := make(chan string)
go func() {
for line := range lines {
if *includePorts {
matches := ipv4Regex.FindAllString(line, -1)
matches = append(matches, ipv6Regex.FindAllString(line, -1)...)
for _, match := range matches {
if isValidIP(match) || isValidIPWithPort(match) {
results <- match
}
}
} else {
matches := ipv4Regex.FindAllStringSubmatch(line, -1)
for _, match := range matches {
if isValidIP(match[1]) {
results <- match[1]
}
}
matches = ipv6Regex.FindAllStringSubmatch(line, -1)
for _, match := range matches {
if isValidIP(match[1]) {
results <- match[1]
}
}
}
}
close(results)
}()
go func() {
for result := range results {
fmt.Println(result)
}
}()
for scanner.Scan() {
lines <- scanner.Text()
}
close(lines)
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error reading from stdin:", err)
}
}
func isValidIPWithPort(s string) bool {
host, port, err := net.SplitHostPort(s)
if err != nil {
return false
}
return isValidIP(host) && isValidPort(port)
}
func isValidIP(s string) bool {
return net.ParseIP(s) != nil
}
func isValidPort(port string) bool {
re := regexp.MustCompile(`^\d+$`)
if !re.MatchString(port) {
return false
}
p, err := strconv.Atoi(port)
if err != nil || p < 1 || p > 65535 {
return false
}
return true
}