11.9 Get the Client IP Address from a Socket Connection


Problem

The server application needs to determine the client IP address after it accepts a connection.

Solution

Use the AcceptSocket method of the TcpListener class to get a lower-level System.Net.Sockets.Socket class instead of a TcpClient . Use the Socket.RemoteEndPoint property to get the client's IP address.

Discussion

The TcpClient class doesn't allow you to retrieve the underlying socket or any information about the client's port and IP address. The TcpClient does provide a Socket property, but this property is protected and therefore not accessible from nonderived classes. To access the underlying socket, you have two options.

  • Create a custom class that derives from TcpClient . This class can access the protected Socket property and expose it through a new property. You must then use this custom class instead of the TcpClient .

  • Bypass the TcpClient class by using the TcpListener.AcceptSocket method. You can still use the higher-level BinaryWriter and BinaryReader classes to write and read data, but you'll need to create the NetworkStream first, using the socket.

This recipe uses the second approach. Following is a revised version of the server code from recipe 11.8, with the changed code emphasized .

 using System; using System.Net; using System.Net.Sockets; using System.IO; using SharedComponent; public class TcpServerTest {     private static void Main() {         // Create a new listener on port 8000.         TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"),            8000);                      Console.WriteLine("About to initialize port.");         listener.Start();         Console.WriteLine("Listening for a connection...");                      try {  // Wait for a connection request,   // and return a Socket initialized for communication.   Socket socket = listener.AcceptSocket();  Console.WriteLine("Connection accepted.");  // Create the network stream.   NetworkStream stream = new NetworkStream(socket);  // Create a BinaryWriter for writing to the stream.             BinaryWriter w = new BinaryWriter(stream);                              // Create a BinaryReader for reading from the stream.             BinaryReader r = new BinaryReader(stream);                              if (r.ReadString() == ClientMessages.RequestConnect) {                 w.Write(ServerMessages.AcknowledgeOK);                 Console.WriteLine("Connection completed.");  // Get the client IP.   Console.WriteLine("The client is from IP address: " +   ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());   Console.Write("The client uses local port: " +   ((IPEndPoint)socket.RemoteEndPoint).Port.ToString());    while (r.ReadString() != ClientMessages.Disconnect)                 {}                 Console.WriteLine();                 Console.WriteLine("Disconnect request received.");                 w.Write(ServerMessages.Disconnect);             } else {                 Console.WriteLine("Could not complete connection.");             }             // Close the connection socket.  socket.Close();    Console.WriteLine("Connection closed.");             // Close the underlying socket (stop listening for new requests).             listener.Stop();             Console.WriteLine("Listener stopped.");         } catch (Exception err) {             Console.WriteLine(err.ToString());         }                  Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net