简体   繁体   English

自动获取IP地址的AC#套接字

[英]A C# Socket that gets an IP address automatically

I've started socket programming with C#. 我已经开始使用C#进行套接字编程。 Previously, I had some experience working with sockets under Java; 以前,我在Java下使用套接字有一些经验。 and everything is fine with C# too except that: 使用C#一切都很好,除了:

C# sockets don't acquire IP address automatically. C#套接字不会自动获取IP地址。 In Java, server sockets only need a port, and then when they are constructed, the automatically acquire a usable IP that can be returned by a method (I don't remember the name of that method). 在Java中,服务器套接字只需要一个端口,然后在构造它们时,将自动获取可用方法返回的可用IP(我不记得该方法的名称)。

in C#, a server socket must be given an IP, or otherwise it can't be constructed. 在C#中,必须为服务器套接字分配IP,否则无法构造它。 I want the socket to find an IP automatically, but I tried IPAddress.any , and it only returns 0.0.0.0 which is just weird (I don't even know what that means! Listening on every IP?) IP address of the server socket can be returned by localEndPoint property, so I just want the socket to grab an IP and then I'll figure what it is using that method. 我希望套接字自动查找IP,但是我尝试了IPAddress.any ,它只返回0.0.0.0 ,这很奇怪(我什至不知道这意味着什么!在每个IP上侦听?)服务器的IP地址套接字可以由localEndPoint属性返回,所以我只想让套接字获取IP,然后我会弄清楚它使用的是哪种方法。

How is this possible ? 这怎么可能 ?

As noted in the comments. 如评论中所述。 the 0.0.0.0 means "any ip address", which is exactly what you indicated in your constructor. 0.0.0.0的意思是“任何ip地址”,这恰好是您在构造函数中指示的内容。

If you want it to only listen on a specific IP, you need to explicitly denote that IP in the constructor. 如果希望它仅侦听特定IP,则需要在构造函数中显式表示该IP。 It won't pick one at random, and you shouldn't want it to. 它不会随机选择一个,并且您不希望这样做。

Incidentally, there is a different class for listing the IPs available on a system. 顺便说一句,有一个不同的类来列出系统上可用的IP。 Let me know in a comment if that's what you need. 如果需要,请在评论中告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM