utils-other.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package comm
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. )
  11. func GetFreePort() (int, error) {
  12. addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
  13. if err != nil {
  14. return 0, err
  15. }
  16. l, err := net.ListenTCP("tcp", addr)
  17. if err != nil {
  18. return 0, err
  19. }
  20. defer l.Close()
  21. return l.Addr().(*net.TCPAddr).Port, nil
  22. }
  23. func GetLocalIpByName(adapterName string) net.IP {
  24. ifaces, err := net.Interfaces()
  25. // handle err
  26. if err != nil {
  27. log.Println("No network:", err)
  28. return nil
  29. }
  30. for _, i := range ifaces {
  31. if strings.Contains(i.Name, adapterName) {
  32. addrs, err := i.Addrs()
  33. if err != nil {
  34. log.Println("No IP:", err)
  35. return nil
  36. }
  37. for _, addr := range addrs {
  38. var ip net.IP
  39. switch v := addr.(type) {
  40. case *net.IPNet:
  41. log.Println("IPNET")
  42. ip = v.IP
  43. case *net.IPAddr:
  44. log.Println("IPAddr")
  45. ip = v.IP
  46. }
  47. if ip[0] == 0 {
  48. log.Println("Get device:", i.Name)
  49. return ip
  50. }
  51. }
  52. }
  53. }
  54. return nil
  55. }
  56. func IsExist(path string) bool {
  57. _, err := os.Stat(path)
  58. if err != nil {
  59. if os.IsExist(err) {
  60. return true
  61. }
  62. if os.IsNotExist(err) {
  63. return false
  64. }
  65. fmt.Println(err)
  66. return false
  67. }
  68. return true
  69. }
  70. func CreateSessionId() string {
  71. t := time.Now()
  72. date := t.Format("20060102150405")
  73. return fmt.Sprintf("s%s-%d", date, t.Nanosecond())
  74. }
  75. func GetCurrentDir() string {
  76. dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
  77. if err != nil {
  78. return ""
  79. }
  80. return strings.Replace(dir, "\\", "/", -1)
  81. }