dip/functions.go

104 lines
2.2 KiB
Go
Raw Normal View History

2019-12-22 18:20:45 +01:00
package main
import (
"flag"
"fmt"
"net"
"net/http"
2019-12-22 18:20:45 +01:00
"os"
"strings"
2020-01-19 23:33:22 +01:00
"log"
2019-12-22 18:20:45 +01:00
"github.com/labstack/echo/v4"
"github.com/likexian/whois-go"
whoisparser "github.com/likexian/whois-parser-go"
)
// GetIPInfo returns IP address informations
func GetIPInfo(c echo.Context) (ip IP, err error) {
if c.QueryParam("ip") != "" {
ip.IP = c.QueryParam("ip")
} else {
ip.IP = c.RealIP()
}
err = ip.CheckIPAddress()
if err != nil {
2020-01-19 23:33:22 +01:00
log.Println(fmt.Sprintf("Error checking IP address %s",ip.IP))
2019-12-22 18:20:45 +01:00
}
err = ip.GetHostname()
if err != nil {
2020-01-19 23:33:22 +01:00
log.Println(fmt.Sprintf("Error checking revers DNS for IP address %s",ip.IP))
2019-12-22 18:20:45 +01:00
}
return
}
// Dip return webpage
func Dip(c echo.Context) (err error) {
2019-12-22 18:20:45 +01:00
var ip IP
2019-12-22 18:20:45 +01:00
ip, err = GetIPInfo(c)
2020-01-19 23:33:22 +01:00
fmt.Println(err)
2019-12-22 18:20:45 +01:00
if err != nil {
return c.Render(http.StatusInternalServerError, "error.html", nil)
2019-12-22 18:20:45 +01:00
}
if strings.Contains(c.Request().Header.Get(echo.HeaderAccept), echo.MIMETextHTML) {
return c.Render(http.StatusOK, "index.html", ip)
} else {
return c.JSON(http.StatusOK, ip)
2019-12-22 18:20:45 +01:00
}
}
// Static returns static files
func Static(c echo.Context) (err error) {
//static := c.Param("static")
return c.Render(http.StatusOK, "static/js/uikit-icons.js", "")
}
// CheckIPAddress check if ip is an IP address, return err if there's an error
2019-12-22 18:20:45 +01:00
func (ip *IP) CheckIPAddress() (err error) {
addr := net.ParseIP(ip.IP)
if addr == nil {
return fmt.Errorf("Supplied string isn't an IP address")
}
return
}
// GetHostname assign ip.Hostname value
func (ip *IP) GetHostname() (err error) {
revip, err := net.LookupAddr(ip.IP)
if err != nil {
return fmt.Errorf(fmt.Sprintf("Supplied address %s doesn't have a valid reverse DNS entry", ip.IP))
}
ip.Hostname = revip[0]
return
}
// GetWhois not implemented yet
2019-12-22 18:20:45 +01:00
func (ip *IP) GetWhois() (err error) {
resultraw, err := whois.Whois("example.com")
2019-12-22 18:20:45 +01:00
//resultraw, err := whois.Whois(ip.IP)
fmt.Println(resultraw)
result, err := whoisparser.Parse(resultraw)
if err != nil {
return
}
fmt.Println(result)
return
}
// Usage displays possible arguments
func Usage() {
flag.PrintDefaults()
os.Exit(1)
}
// IP defines dip main struct
2019-12-22 18:20:45 +01:00
type IP struct {
IP string `json:"ip"`
Hostname string `json:"hostname"`
}