package main
import(
"os/exec"
"fmt"
)
func main(){
fmt.Println(PortInUse(9001))
}
func PortInUse(port int) bool {
checkStatement := fmt.Sprintf("lsof -i:%d ", port)
output, _ := exec.Command("sh", "-c", checkStatement).CombinedOutput()
if len(output) > 0 {
return true
}
return false
}
- 获取外网ip地址
https://transidc.com/?mod=support&type=detail&id=43 (仅用于测试)
- ipv4校验
package main
import (
"fmt"
"net"
)
func isValidIPv4(ip string) bool {
return net.ParseIP(ip).To4() != nil
}
func main() {
validIP := "192.168.1.1"
invalidIP := "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
fmt.Printf("Is %s a valid IPv4 address? %t\n", validIP, isValidIPv4(validIP))
fmt.Printf("Is %s a valid IPv4 address? %t\n", invalidIP, isValidIPv4(invalidIP))
}
- 判断http请求是从内网还是外网发起
package main
import (
"fmt"
"net"
"net/http"
)
func isPrivateIP(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
ip4 := ip.To4()
if ip4 == nil {
return false
}
return ip4[0] == 10 || // 10.x.x.x
(ip4[0] == 172 && (ip4[1] >= 16 && ip4[1] <= 31)) || // 172.16.x.x - 172.31.x.x
(ip4[0] == 192 && ip4[1] == 168) // 192.168.x.x
}
func handler(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
ip = xff
}
host, _, err := net.SplitHostPort(ip)
if err != nil {
fmt.Fprintf(w, "Failed to parse IP: %v\n", err)
return
}
if isPrivateIP(net.ParseIP(host)) {
fmt.Fprintf(w, "Local IP Access\n")
} else {
fmt.Fprintf(w, "External IP Access\n")
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
另外,可以根据http协议原理,从request的host字段中直接拿到请求的ip地址。
0 条评论