日期:2014-05-18  浏览次数:21176 次

C# 用Socket怎么得到请求客户端的IP地址??
我的Server里面的监听函数是:
private void BeginListen()
  {
  IPAddress ServerIp = GetServerIP();
  IPEndPoint iep = new IPEndPoint(ServerIp, 8000);
  socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  byte[] byteMessage = new byte[13];
  socket.Bind(iep);
  while (true)
  {
  try
  {
  socket.Listen(5);
  Socket newSocket = socket.Accept();
  newSocket.Receive(byteMessage);
  string ClientIP= Encoding.ASCII.GetString(byteMessage);
  MessageBox.Show(msg);
  }
  catch (SocketException ex)
  {
  ex.ToString();
  }

  }

  } 

客户端程序怎么写??

当客户端发送请求的时候,我如何得到客户端的IP 地址>?

------解决方案--------------------
客户端发请求的时候把客户端IP和端口都发来不就可以了吗
比如,发来请求开头是"192.168.100.101_8888_",然后split('_')就得到了
------解决方案--------------------
倒...
Socket有一个RemoteEndPoint属性...
至于客户端怎么写...
------解决方案--------------------
http://www.csharp-examples.net/socket-send-receive/
------解决方案--------------------
Socket newSocket = socket.Accept(); 
IPEndPoint clientipe = (IPEndPoint)newSocket.RemoteEndPoint;
Console.WriteLine("[" + clientipe.Address.ToString() + "] Connected");