@@ -2,10 +2,12 @@ package api
22
33import (
44 "encoding/json"
5- "github.com/The-NeXT-Project/NetStatus-API-Go/config"
65 "net"
76 "net/http"
7+ "strconv"
88 "time"
9+
10+ "github.com/The-NeXT-Project/NetStatus-API-Go/config"
911)
1012
1113func TcpingV1 (writer http.ResponseWriter , request * http.Request ) {
@@ -41,27 +43,60 @@ func TcpingV1(writer http.ResponseWriter, request *http.Request) {
4143 return
4244 }
4345
44- status , msg := ping (request .URL .Query ().Get ("ip" ), request .URL .Query ().Get ("port" ))
46+ ip := request .URL .Query ().Get ("ip" )
47+ portStr := request .URL .Query ().Get ("port" )
48+
49+ // Sanitize IP address
50+ if net .ParseIP (ip ) == nil {
51+ res , _ := json .Marshal (tcpingRes {
52+ Status : "false" ,
53+ Message : "Invalid IP address format" ,
54+ })
55+ writer .Header ().Set ("Content-Type" , "application/json" )
56+ writer .WriteHeader (http .StatusBadRequest )
57+ _ , err := writer .Write (res )
58+ if err != nil {
59+ writer .WriteHeader (http .StatusInternalServerError )
60+ }
61+ return
62+ }
63+
64+ // Sanitize port
65+ port , err := strconv .Atoi (portStr )
66+ if err != nil || port < 1 || port > 65535 {
67+ res , _ := json .Marshal (tcpingRes {
68+ Status : "false" ,
69+ Message : "Invalid port number" ,
70+ })
71+ writer .Header ().Set ("Content-Type" , "application/json" )
72+ writer .WriteHeader (http .StatusBadRequest )
73+ _ , _ = writer .Write (res ) // Error handling for Write is already present below
74+ return
75+ }
76+
77+ status , latency , msg := ping (ip , portStr )
4578
4679 res , _ := json .Marshal (tcpingRes {
4780 Status : status ,
81+ Time : latency ,
4882 Message : msg ,
4983 })
5084
5185 writer .Header ().Set ("Content-Type" , "application/json" )
5286 writer .WriteHeader (http .StatusOK )
53- _ , err : = writer .Write (res )
87+ _ , err = writer .Write (res )
5488 if err != nil {
5589 writer .WriteHeader (http .StatusInternalServerError )
5690 }
5791}
5892
59- func ping (ip string , port string ) (status string , msg string ) {
93+ func ping (ip string , port string ) (string , int , string ) {
6094 timeout := time .Duration (int64 (config .Config .TcpingTimeout ) * int64 (time .Millisecond ))
95+ startTime := time .Now ()
6196
6297 conn , err := net .DialTimeout ("tcp" , net .JoinHostPort (ip , port ), timeout )
6398 if err != nil {
64- return "false" , "TCP connection failed"
99+ return "false" , config . Config . TcpingTimeout , "TCP connection failed"
65100 }
66101
67102 if conn != nil {
@@ -70,5 +105,5 @@ func ping(ip string, port string) (status string, msg string) {
70105 }(conn )
71106 }
72107
73- return "true" , "TCP connection successful"
108+ return "true" , int ( time . Since ( startTime ). Milliseconds ()), "TCP connection successful"
74109}
0 commit comments