C# 获取远程套接字端点的 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1904160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:44:45  来源:igfitidea点击:

Getting the IP Address of a Remote Socket Endpoint

c#socketsendpoints

提问by bobber205

How do I determine the remote IP Address of a connected socket?

如何确定已连接套接字的远程 IP 地址?

I have a RemoteEndPoint object I can access and well as its AddressFamily member.

我有一个可以访问的 RemoteEndPoint 对象及其 AddressFamily 成员。

How do I utilize these to find the ip address?

我如何利用这些来查找 IP 地址?

Thanks!

谢谢!

Currently trying

目前正在尝试

IPAddress.Parse( testSocket.Address.Address.ToString() ).ToString();

and getting 1.0.0.127 instead of 127.0.0.1 for localhost end points. Is this normal?

并为本地主机端点获取 1.0.0.127 而不是 127.0.0.1。这是正常的吗?

采纳答案by Cory Charlton

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx

You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.

然后,您可以调用 IPEndPoint..::.Address 方法来检索远程 IPAddress,并调用 IPEndPoint..::.Port 方法来检索远程端口号。

More from the link (fixed up alot heh):

更多来自链接(修复了很多呵呵):

Socket s;

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;

if (remoteIpEndPoint != null)
{
    // Using the RemoteEndPoint property.
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}

if (localIpEndPoint != null)
{
    // Using the LocalEndPoint property.
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}

回答by Bertrand Marron

RemoteEndPoint is a property, its type is System.Net.EndPointwhich inherits from System.Net.IPEndPoint.

RemoteEndPoint 是一个属性,它的类型是System.Net.EndPoint,它继承自System.Net.IPEndPoint

If you take a look at IPEndPoint's members, you'll see that there's an Addressproperty.

如果您查看 IPEndPoint 的members,您会看到有一个Address属性。

回答by user3235770

string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();

回答by Mar?al Torà

I've made this code in VB.NET but you can translate. Well pretend you have the variable Clientas a TcpClient

我已经在 VB.NET 中制作了这段代码,但您可以翻译。好吧,假设您将变量Client作为TcpClient

Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))

Hope it helps! Cheers.

希望能帮助到你!干杯。