The direction of data transfer has nothing to do with listening and knowing IP address. (Besides, you can create two channels: in one channel you can pass client IP and later create another channel, where a client listens. However, let me tell about it in proper order…)
To establish communication you should listen on one side and connect on another side. Let's call listening side "server" and connecting side "client". You should understand though, that the same application can play a role of a server and a client at the same time, or represent several "clients" or several "servers", or any combination, at the same time. (Only a traditional "client-server" model does not use those combinations, but this is a very bad simple model, one of the reasons why Web application development is so difficult; but we cannot discuss it here in detail.) All you need is a separate thread for each activity, normally, two threads per listener (it's a common mistake to use one) and one per client.
To listen, you need the class
System.Net.Sockets.TcpListener
, to connect to listening application, you need the class
System.Net.Sockets.TcpClient
:
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx[
^].
Even in the primitive "client-server" model, on the server side, you listen for new connection (in a separate thread), and use another thread to read/write from/to a network stream. More exactly, you can accept a socket and obtain the socket instance representing a remote (client) socket, or accept an instance of
TcpClient
, representing the connected remote TCP client. You can accept in a loop in your accepting thread, to allow other clients to connect.
You can share the instances of the
TcpClient
or
System.Net.Sockets.Socket
(in general case, some collection of instances) with another thread which does read/write operations. (Don't forget to use
mutual exclusion, for example, with
lock
statements.) This thread, as well as the communication thread on the "client" side, should implement some protocol of interlacing read/write operation. Even if you don't call it a protocol, such thing always exists. This is some
application layer protocol:
http://en.wikipedia.org/wiki/Application_layer[
^].
As you can see, even if you have one channel, both "client" and "server" reads and writes in sequence.
And finally, let me get back to the idea of "inverted" channel. You can start listening on what was initially a "client". You create two more threads and start listening, playing the role of the "server" as well. You already have one channel. Its application protocol can include the mechanism of passing of the IP address (port or whatever else) to the "service". The "server" part can play the role of the client and connect to the "client".
See also my past answer:
Multple clients from same port Number[
^].
—SA