赞
踩
在C#中,可以使用Socket
类的RemoteEndPoint
属性来获取连接的远程IP地址和端口号。以下是一个简单的示例代码,展示了如何从一个已连接的Socket
实例中提取IP地址和端口号:
- using System;
- using System.Net;
- using System.Net.Sockets;
-
- public class SocketExample
- {
- public static void Main()
- {
- // 假设socket是一个已连接的Socket实例
- Socket socket = ...; // 获取或创建Socket实例
-
- // 获取远程端点信息
- EndPoint remoteEndPoint = socket.RemoteEndPoint;
-
- // 将EndPoint转换为IPEndPoint以获取IP和端口
- IPEndPoint endPoint = remoteEndPoint as IPEndPoint;
- if (endPoint != null)
- {
- IPAddress ipAddress = endPoint.Address;
- int port = endPoint.Port;
-
- Console.WriteLine("IP Address: " + ipAddress);
- Console.WriteLine("Port: " + port);
- }
- else
- {
- Console.WriteLine("Unable to obtain remote IP and port information.");
- }
- }
- }

确保替换掉注释中的...
,以获取或创建一个有效的Socket
实例。这段代码将输出连接的远程IP地址和端口号。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。