Socket.LocalEndPoint 属性

定义

获取本地终结点。

C#
public System.Net.EndPoint LocalEndPoint { get; }
C#
public System.Net.EndPoint? LocalEndPoint { get; }

属性值

EndPoint 当前用以进行通信的 Socket

例外

尝试访问套接字时出错。

示例

下面的代码示例检索并显示本地终结点和远程终结点。

C#
s.Connect(lep);

// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)s.RemoteEndPoint).Address.ToString()) + "on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString());

// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + IPAddress.Parse(((IPEndPoint)s.LocalEndPoint).Address.ToString()) + "I am connected on port number " + ((IPEndPoint)s.LocalEndPoint).Port.ToString());

注解

属性 LocalEndPoint 获取一个 EndPoint ,其中包含绑定到 Socket 的本地 IP 地址和端口号。 在检索任何信息之前,必须将其EndPointIPEndPoint强制转换为 。 然后,可以调用 方法来检索本地 IPAddress,并IPEndPoint.Port调用 IPEndPoint.Address 方法来检索本地端口号。

属性 LocalEndPoint 通常是在调用 方法后设置的 Bind 。 如果允许系统分配套接字的本地 IP 地址和端口号, LocalEndPoint 则会在第一次 I/O 操作后设置 属性。 对于面向连接的协议,第一个 I/O 操作是调用 ConnectAccept 方法。 对于无连接协议,第一个 I/O 操作将是任何发送或接收调用。

备注

如果收到 , SocketException请使用 SocketException.ErrorCode 属性获取特定的错误代码。 获取此代码后,请参阅 Windows 套接字版本 2 API 错误代码 文档,获取错误的详细说明。

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。 有关详细信息,请参阅 .NET Framework 中的网络跟踪

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅