sip.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package utils
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "net"
  7. "runtime"
  8. "time"
  9. )
  10. func RandNum16String(n int) string {
  11. numbers16 := "0123456789abcdef"
  12. return randStringBySoure(numbers16, n)
  13. }
  14. func RandNumString(n int) string {
  15. numbers := "0123456789"
  16. return randStringBySoure(numbers, n)
  17. }
  18. func RandString(n int) string {
  19. letterBytes := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  20. return randStringBySoure(letterBytes, n)
  21. }
  22. // https://github.com/kpbird/golang_random_string
  23. func randStringBySoure(src string, n int) string {
  24. randomness := make([]byte, n)
  25. rand.Seed(time.Now().UnixNano())
  26. _, err := rand.Read(randomness)
  27. if err != nil {
  28. panic(err)
  29. }
  30. l := len(src)
  31. // fill output
  32. output := make([]byte, n)
  33. for pos := range output {
  34. random := randomness[pos]
  35. randomPos := random % uint8(l)
  36. output[pos] = src[randomPos]
  37. }
  38. return string(output)
  39. }
  40. // Error Error
  41. type Error struct {
  42. err error
  43. params []interface{}
  44. }
  45. func (err *Error) Error() string {
  46. if err == nil {
  47. return "<nil>"
  48. }
  49. str := fmt.Sprint(err.params...)
  50. if err.err != nil {
  51. str += fmt.Sprintf(" err:%s", err.err.Error())
  52. }
  53. return str
  54. }
  55. // NewError NewError
  56. func NewError(err error, params ...interface{}) error {
  57. return &Error{err, params}
  58. }
  59. func PrintStack() {
  60. var buf [4096]byte
  61. n := runtime.Stack(buf[:], false)
  62. fmt.Printf("==> %s\n", string(buf[:n]))
  63. }
  64. // ResolveSelfIP ResolveSelfIP
  65. func ResolveSelfIP() (net.IP, error) {
  66. ifaces, err := net.Interfaces()
  67. if err != nil {
  68. return nil, err
  69. }
  70. for _, iface := range ifaces {
  71. if iface.Flags&net.FlagUp == 0 {
  72. continue // interface down
  73. }
  74. if iface.Flags&net.FlagLoopback != 0 {
  75. continue // loopback interface
  76. }
  77. addrs, err := iface.Addrs()
  78. if err != nil {
  79. return nil, err
  80. }
  81. for _, addr := range addrs {
  82. var ip net.IP
  83. switch v := addr.(type) {
  84. case *net.IPNet:
  85. ip = v.IP
  86. case *net.IPAddr:
  87. ip = v.IP
  88. }
  89. if ip == nil || ip.IsLoopback() {
  90. continue
  91. }
  92. ip = ip.To4()
  93. if ip == nil {
  94. continue // not an ipv4 address
  95. }
  96. return ip, nil
  97. }
  98. }
  99. return nil, errors.New("server not connected to any network")
  100. }