-
Notifications
You must be signed in to change notification settings - Fork 50
/
robowhois.go
85 lines (76 loc) · 2.24 KB
/
robowhois.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
// Copyright (c) 2014 RightScale, Inc. - see LICENSE
package whois
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"regexp"
)
//DataPart host/body of data
type DataPart struct {
Body string `json:"body"`
Host string `json:"host"`
}
//DataResponse daystamp and parts
type DataResponse struct {
Daystamp string `json:"daystamp"`
Parts []DataPart `json:"parts"`
}
//Data is response body
type Data struct {
Response DataResponse `json:"response"`
}
var orgNameRe = regexp.MustCompile("Org[^a-zA-Z]?Name[^a-zA-Z]*([ -~]*)")
var netNameRe = regexp.MustCompile("network:Organization[^a-zA-Z]*([ -~]*)")
//Whois determines ip information from robowhois
func Whois(ipAddr, apiToken string) string {
result := ""
if net.ParseIP(ipAddr) == nil {
fmt.Printf("IP Address: %s - Invalid\n", ipAddr)
result = ""
} else {
fmt.Printf("IP Address: %s - Valid\n", ipAddr)
validIpAddr := net.ParseIP(ipAddr).String()
url := fmt.Sprint("http://api.robowhois.com/v1/whois/", validIpAddr, "/parts")
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("robowhois: error building URL for query for %s", validIpAddr)
result = ""
}
req.SetBasicAuth(apiToken, "X")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("robowhois: query for %s failed: %s", validIpAddr, err)
result = ""
}
if resp.StatusCode != 200 {
log.Printf("robowhois: query for %s returned error: %s", validIpAddr, resp.Status)
result = ""
}
var data Data
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
log.Printf("robowhois: can't decode response for %s: %s", validIpAddr, err)
result = ""
}
n := len(data.Response.Parts)
//log.Printf("robowhois: %s -> %s", ipAddr, data.Response.Parts[n-1].Body)
match := orgNameRe.FindAllStringSubmatch(data.Response.Parts[n-1].Body, -1)
if match == nil {
match = netNameRe.FindAllStringSubmatch(data.Response.Parts[n-1].Body, -1)
}
if match == nil {
log.Printf("robowhois: can't find OrgName in response for %s", validIpAddr)
result = ""
}
result = match[len(match)-1][1]
log.Printf("robowhois: %s -> %s", validIpAddr, result)
}
return result
}
func testMain() {
fmt.Printf("%s -> %s\n", os.Args[1], Whois(os.Args[1], os.Args[2]))
}