How to listen on multiple IP addresses?

后端 未结 6 1206
别那么骄傲
别那么骄傲 2021-02-15 16:15

If my server has multiple IP addresses assigned to it, and I would like to listen to some (or all) of them, how do I go about doing that?

Do I need to create a new socke

相关标签:
6条回答
  • 2021-02-15 16:53

    You cannot bind a single socket to multiple endpoints. A SocketException (invalid argument error) occurs the second time you call Bind() for a given socket.

    As others have said, you can use IPAddress.Any to listen to the IPv4 addresses on the local machine. However, if you only want to listen on a subset of the available IP addresses, you'll have to create separate sockets.

    0 讨论(0)
  • 2021-02-15 16:57

    Technically, your server never has any IP addresses assigned to it.

    Instead, individual network interfaces may be assigned IP addresses. Usually, each NIC gets one IP address, but that's just the most common case.

    If you want to control which interfaces are listening for incoming connections on your chosen port, you'll need to create a separate socket for each one.

    0 讨论(0)
  • 2021-02-15 16:59

    Yes, IPAddress.Any will listen on all interfaces.

    http://msdn.microsoft.com/en-us/library/system.net.ipaddress.any.aspx

    0 讨论(0)
  • 2021-02-15 17:00

    If you want to listen on all IPv4 and IPv6 addresses, use this code:

    var listener = new TcpListener(IPAddress.IPv6Any, port);
    listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
    

    IPv6Any tells Windows to listen on the IPv6 stack. Setting the socket option to false tells Windows to not limit itself to the IPv6 stack, but rather to also listen on the IPv4 stack. The default is to only listen on the stack explicitly specified.

    0 讨论(0)
  • 2021-02-15 17:00

    The MSDN library does seem contradcitory regarding IPAddress.Any. The Bind doc

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

    says that the 'most suitable' address is chosen, but the IPAddress.Any doc

    http://msdn.microsoft.com/en-us/library/system.net.ipaddress.any.aspx

    says that with this constant the socket must listen for activity on all interfaces.

    However, I'm told that it's the IPAddress.Any doc that is correct.

    (adding this as an answer since I don't have enough rep to leave comments).

    0 讨论(0)
  • 2021-02-15 17:01

    I have worked on it, IPAddress.Any is not the proper way, It will bind any Suitable IP address. In my case I have 2 NIC and I couldn't trouble shoot the problem. When I added

    System.Net.IPAddress ipAddress = IPAddress.Parse("xxx.xxx.xxx.xxx");
    listener = new TcpListener(ipAddress, portNum);
    

    It worked fine.

    0 讨论(0)
提交回复
热议问题