mirror of
https://github.com/dcarrillo/whatismyip.git
synced 2025-07-01 22:09:26 +00:00
Add endopoint to check is a given port is open on the client (#22)
This commit is contained in:
54
router/port_scanner.go
Normal file
54
router/port_scanner.go
Normal file
@ -0,0 +1,54 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/dcarrillo/whatismyip/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type JSONScanResponse struct {
|
||||
IP string `json:"ip"`
|
||||
Port int `json:"port"`
|
||||
Reachable bool `json:"reachable"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func scanTCPPort(ctx *gin.Context) {
|
||||
port, err := strconv.Atoi(ctx.Params.ByName("port"))
|
||||
if err == nil && (port < 1 || port > 65535) {
|
||||
err = fmt.Errorf("%d is not a valid port number", port)
|
||||
}
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, JSONScanResponse{
|
||||
Reason: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
add := net.TCPAddr{
|
||||
IP: net.ParseIP(ctx.ClientIP()),
|
||||
Port: port,
|
||||
}
|
||||
|
||||
scan := service.PortScanner{
|
||||
Address: &add,
|
||||
}
|
||||
|
||||
isOpen, err := scan.IsPortOpen()
|
||||
reason := ""
|
||||
if err != nil {
|
||||
reason = err.Error()
|
||||
}
|
||||
|
||||
response := JSONScanResponse{
|
||||
IP: ctx.ClientIP(),
|
||||
Port: port,
|
||||
Reachable: isOpen,
|
||||
Reason: reason,
|
||||
}
|
||||
ctx.JSON(http.StatusOK, response)
|
||||
}
|
@ -22,6 +22,7 @@ func SetupTemplate(r *gin.Engine) {
|
||||
// Setup defines the endpoints
|
||||
func Setup(r *gin.Engine) {
|
||||
r.GET("/", getRoot)
|
||||
r.GET("/scan/tcp/:port", scanTCPPort)
|
||||
r.GET("/client-port", getClientPortAsString)
|
||||
r.GET("/geo", getGeoAsString)
|
||||
r.GET("/geo/:field", getGeoAsString)
|
||||
|
Reference in New Issue
Block a user