BrandonPotter / SimpleTCP

Straightforward .NET library to handle the repetitive tasks of spinning up and working with TCP sockets (client and server).
Apache License 2.0
365 stars 108 forks source link

Getting the IP and Port of client #28

Open ZengerU opened 6 years ago

ZengerU commented 6 years ago

Excuse me for the naive(?) question, i have little to no experience in c#. In the DataRecieved function, is there a way for the server to get the ip and the port of the sender object? Or any other way?

Thanks in advance!

davi2td commented 6 years ago

Best way to understand is break right after your datareceived function then look at e in debugger. Here's an example:

LantronixServer.DelimiterDataReceived += ReceivedLineTCP; //Create DataReceived handler

Sub ReceivedLineTCP(sender As object, e As Message);
try
{
//You have to convert RemoteEndPoint to IPEndpoint
//Then do whatever with IPEndpoint
var ip = ((Net.IPEndPoint)e.TcpClient.Client.RemoteEndPoint).Address.ToString();
}
catch (Exception ex)
{
            logger.Error(ex.Message.ToString());
        }
    }
harleyknd1 commented 6 years ago

Clients don't have a "receiving port" by default, they'll just open a random free port to send the message and close it when the message is send, so there's no reliable return port.

You'd be better of having the server return a port to the client and the client starting its own listen server, and announcing its own port and ip to the server once it starts listening for incoming messages...