1. // 请先在当前目录执行以下命令初始化 Go 模块:
  2. // go mod init fileserver
  3. // go run main.go -dir /Users/WebScoop/packs/ -port 8099 //这样子使用
  4. package main
  5. import (
  6. "flag"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "strings"
  12. )
  13. func main() {
  14. dir := flag.String("dir", ".", "要共享的目录路径")
  15. port := flag.String("port", "8080", "监听端口")
  16. flag.Parse()
  17. fs := http.FileServer(http.Dir(*dir))
  18. http.Handle("/", fs)
  19. addr := ":" + *port
  20. lanIPs := make([]string, 0)
  21. otherIPs := make([]string, 0)
  22. seenIPs := make(map[string]struct{})
  23. routeIP := ""
  24. // UDP Dial 只用于让系统选择默认出站网卡,不会实际发送数据包。
  25. if conn, err := net.Dial("udp4", "8.8.8.8:80"); err == nil {
  26. if udpAddr, ok := conn.LocalAddr().(*net.UDPAddr); ok {
  27. if ip := udpAddr.IP.To4(); ip != nil && ip.IsPrivate() {
  28. routeIP = ip.String()
  29. }
  30. }
  31. conn.Close()
  32. }
  33. ifaces, err := net.Interfaces()
  34. if err != nil {
  35. log.Printf("获取本机内网 IP 失败: %v", err)
  36. } else {
  37. for _, iface := range ifaces {
  38. if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
  39. continue
  40. }
  41. isLANInterface := iface.Flags&net.FlagBroadcast != 0 && iface.Flags&net.FlagPointToPoint == 0
  42. addrs, err := iface.Addrs()
  43. if err != nil {
  44. log.Printf("读取网卡 %s 地址失败: %v", iface.Name, err)
  45. continue
  46. }
  47. for _, networkAddr := range addrs {
  48. var ip net.IP
  49. switch v := networkAddr.(type) {
  50. case *net.IPAddr:
  51. ip = v.IP
  52. case *net.IPNet:
  53. ip = v.IP
  54. }
  55. ip = ip.To4()
  56. if ip == nil || !ip.IsPrivate() {
  57. continue
  58. }
  59. ipText := ip.String()
  60. if _, ok := seenIPs[ipText]; ok {
  61. continue
  62. }
  63. seenIPs[ipText] = struct{}{}
  64. if isLANInterface {
  65. lanIPs = append(lanIPs, ipText)
  66. } else {
  67. otherIPs = append(otherIPs, ipText)
  68. }
  69. }
  70. }
  71. }
  72. if routeIP != "" {
  73. if _, ok := seenIPs[routeIP]; !ok {
  74. seenIPs[routeIP] = struct{}{}
  75. otherIPs = append(otherIPs, routeIP)
  76. }
  77. }
  78. privateIPs := append(lanIPs, otherIPs...)
  79. fmt.Printf("

分类: web

标签: