简体   繁体   中英

A C# Socket that gets an IP address automatically

I've started socket programming with C#. Previously, I had some experience working with sockets under Java; and everything is fine with C# too except that:

C# sockets don't acquire IP address automatically. 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).

in C#, a server socket must be given an IP, or otherwise it can't be constructed. 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.

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.

If you want it to only listen on a specific IP, you need to explicitly denote that IP in the constructor. 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. Let me know in a comment if that's what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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