From 7162e5e45b0fa03d98d2782cf718775eca234747 Mon Sep 17 00:00:00 2001 From: Zack Scholl Date: Wed, 1 May 2019 17:10:02 -0600 Subject: [PATCH] collect ipaddr from connecting to tcp --- src/tcp/tcp.go | 17 +++++++++-------- src/tcp/tcp_test.go | 11 +++++++---- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/tcp/tcp.go b/src/tcp/tcp.go index 43691b0..afb7eb0 100644 --- a/src/tcp/tcp.go +++ b/src/tcp/tcp.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "net" + "strings" "sync" "time" @@ -96,13 +97,12 @@ func (s *server) run() (err error) { func (s *server) clientCommuncation(port string, c *comm.Comm) (err error) { // send ok to tell client they are connected - log.Debugf("sending '%s'", s.banner) - if len(s.banner) > 0 { - err = c.Send([]byte(s.banner)) - } else { - err = c.Send([]byte("ok")) - + banner := s.banner + if len(banner) == 0 { + banner = "ok" } + log.Debugf("sending '%s'", banner) + err = c.Send([]byte(banner + "|||" + c.Connection().RemoteAddr().String())) if err != nil { return } @@ -243,7 +243,7 @@ func pipe(conn1 net.Conn, conn2 net.Conn) { } } -func ConnectToTCPServer(address, room string) (c *comm.Comm, banner string, err error) { +func ConnectToTCPServer(address, room string) (c *comm.Comm, banner string, ipaddr string, err error) { c, err = comm.NewConnection(address) if err != nil { return @@ -253,7 +253,8 @@ func ConnectToTCPServer(address, room string) (c *comm.Comm, banner string, err if err != nil { return } - banner = string(data) + banner = strings.Split(string(data), "|||")[0] + ipaddr = strings.Split(string(data), "|||")[1] log.Debug("sending room") err = c.Send([]byte(room)) if err != nil { diff --git a/src/tcp/tcp_test.go b/src/tcp/tcp_test.go index f048b46..99dce45 100644 --- a/src/tcp/tcp_test.go +++ b/src/tcp/tcp_test.go @@ -1,6 +1,7 @@ package tcp import ( + "strings" "testing" "time" @@ -8,13 +9,15 @@ import ( ) func TestTCP(t *testing.T) { - go Run("debug", "8081") + go Run("debug", "8081", "8082") time.Sleep(100 * time.Millisecond) - c1, _, err := ConnectToTCPServer("localhost:8081", "testRoom") + c1, banner, ipaddr, err := ConnectToTCPServer("localhost:8081", "testRoom") + assert.Equal(t, banner, "8082") + assert.True(t, strings.HasPrefix(ipaddr, "127.0.0.1")) assert.Nil(t, err) - c2, _, err := ConnectToTCPServer("localhost:8081", "testRoom") + c2, _, _, err := ConnectToTCPServer("localhost:8081", "testRoom") assert.Nil(t, err) - _, _, err = ConnectToTCPServer("localhost:8081", "testRoom") + _, _, _, err = ConnectToTCPServer("localhost:8081", "testRoom") assert.NotNil(t, err) // try sending data