tcpip.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package net
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. "time"
  7. )
  8. var KeepAliveInterval = 15 * time.Second
  9. func SplitNetworkType(s string) (string, string, error) {
  10. var (
  11. shecme string
  12. hostPort string
  13. )
  14. result := strings.Split(s, "://")
  15. if len(result) == 2 {
  16. shecme = result[0]
  17. hostPort = result[1]
  18. } else if len(result) == 1 {
  19. hostPort = result[0]
  20. } else {
  21. return "", "", fmt.Errorf("tcp/udp style error")
  22. }
  23. if len(shecme) == 0 {
  24. shecme = "udp"
  25. }
  26. if shecme != "tcp" && shecme != "udp" {
  27. return "", "", fmt.Errorf("scheme should be tcp:// or udp://")
  28. } else {
  29. return shecme, hostPort, nil
  30. }
  31. }
  32. func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
  33. temp := s
  34. hasPort = true
  35. if !strings.Contains(s, ":") && !strings.Contains(s, "]:") {
  36. temp += ":0"
  37. hasPort = false
  38. }
  39. host, port, err = net.SplitHostPort(temp)
  40. return
  41. }
  42. func TCPKeepAlive(c net.Conn) {
  43. if tcp, ok := c.(*net.TCPConn); ok {
  44. _ = tcp.SetKeepAlive(true)
  45. _ = tcp.SetKeepAlivePeriod(KeepAliveInterval)
  46. }
  47. }