You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.0 KiB

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net"
  6. "os"
  7. )
  8. func main() { //client https://systembash.com/a-simple-go-tcp-server-and-tcp-client/
  9. // connect to this socket
  10. conn, _ := net.Dial("tcp", "127.0.0.1:3333")
  11. hostname, err := os.Hostname()
  12. if err != nil {
  13. fmt.Println(err)
  14. os.Exit(1)
  15. }
  16. fmt.Println("connecting to server as hostname:", hostname)
  17. ip := getIp()
  18. fmt.Println("local ip:", ip)
  19. // send to socket
  20. fmt.Fprintf(conn, hostname+", ip: "+ip.String()+"\n")
  21. for {
  22. message, err := bufio.NewReader(conn).ReadString('\n')
  23. if err != nil {
  24. fmt.Println(err)
  25. fmt.Println("server disconnected")
  26. os.Exit(1)
  27. }
  28. fmt.Print("Command from server: " + message)
  29. }
  30. }
  31. func getIp() net.IP {
  32. var ip net.IP
  33. ifaces, err := net.Interfaces()
  34. if err != nil {
  35. fmt.Println(err)
  36. }
  37. for _, i := range ifaces {
  38. addrs, err := i.Addrs()
  39. if err != nil {
  40. fmt.Println(err)
  41. }
  42. for _, addr := range addrs {
  43. switch v := addr.(type) {
  44. case *net.IPNet:
  45. ip = v.IP
  46. case *net.IPAddr:
  47. ip = v.IP
  48. }
  49. // process IP address
  50. }
  51. }
  52. return ip
  53. }