How does a socket know which network interface controller to use?

前端 未结 4 832
慢半拍i
慢半拍i 2020-12-04 17:40

If a computer has multiple network cards, all of them connected to different networks and functioning properly, when we open a socket, how does the OS determine which NIC to

4条回答
  •  感情败类
    2020-12-04 18:11

    As an alternative, you can search for the appropriate nic based on its name:

            //Find the ip address based on the ethernet adapter name. On my machine the ethernet adapter is "Ethernet"
            System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            System.Net.NetworkInformation.NetworkInterface ethernet = nics.Where(n => n.Name.Equals("Ethernet")).Single();
            UnicastIPAddressInformation uniCastIPAddressInformation = ethernet.GetIPProperties().UnicastAddresses.Where(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).Single();
    
            IPEndPoint localEndPoint = new IPEndPoint(uniCastIPAddressInformation.Address, 9000);
    
            //Create a TCP/IP socket.  
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //Bind and start listening
            listener.Bind(localEndPoint);
            listener.Listen(10);
    

提交回复
热议问题