當服務器存在多個與公網訪問的網卡(對應不同的公網IP地址)時,如何使用指定的網卡進行HTTP請求


官方文檔:https://docs.microsoft.com/zh-cn/dotnet/api/system.net.servicepoint.bindipendpointdelegate

參考來源:https://stackoverflow.com/questions/5860893/sending-httpwebrequest-through-a-specific-network-adapter

     http://www.veryhuo.com/a/view/24494.html

有時服務端的主動HTTP請求需要特定的IP地址,但在默認的請求配置中,使用哪個網卡IP地址是不確定的,這時需要主動設置請求所使用的網卡(IP地址),如果使用指定網卡可以按MAC地址查詢網卡,再查詢到網卡的IP地址,如果IP地址固定,則可以直接使用IP地址來指定。

class Program
    {
        public static string SpecificMac1 = "60EE5C1______"; // 192.168.1._
        public static string SpecificMac2 = "380025______"; // 192.168.1._
        public static string SpecificIp1 = "192.168.1._"; // 192.168.1._
        public static string SpecificIp2 = "192.168.1._"; // 192.168.1._
        public static string SpecificMac = "";
        public static string SpecificIp = "";

        // 此方法並不是每次都會調用,而是在刷新 ServicePoint 的時候會調用
        public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
        {
            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (networkInterface.GetPhysicalAddress().ToString() == SpecificMac)
                {
                    if (networkInterface.GetIPProperties().UnicastAddresses.Any())
                    {
                        var info = networkInterface.GetIPProperties().UnicastAddresses.Last();

                        Console.WriteLine("找到的 IP 地址:" + info.Address.ToString());

                        return new IPEndPoint(info.Address, 0);
                    }
                }
            }

            Console.WriteLine("沒找到的 IP 地址?");
            return null;
        }

        public static string Get(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            // 查找 MAC 網卡
            //request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);

            // 指定 IP 地址
            request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint((a, b, c) => new IPEndPoint(IPAddress.Parse(SpecificIp), 0));

            request.Method = "GET";
            var response = (HttpWebResponse)request.GetResponse();
            var stream = response.GetResponseStream();
            if (stream == null)
            {
                return null;
            }
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();
                return result;
            }
        }

        static void Main(string[] args)
        {
            // 更快的刷新 ServicePoint 的 BindIPEndPoint
            ServicePointManager.MaxServicePointIdleTime = 0;

            var url = "http://192.168.1._/ip";
            while (true)
            {
                SpecificMac = SpecificMac1;
                SpecificIp = SpecificIp1;
                var result = Get(url);
                Console.WriteLine("返回內容1:" + result);
                Thread.Sleep(500);

                SpecificMac = SpecificMac2;
                SpecificIp = SpecificIp2;
                result = Get(url);
                Console.WriteLine("返回內容2:" + result);
                Thread.Sleep(500);
            }

            Console.ReadKey();
        }
    }

【擴展】在 TCP、UDP 通信中可能遇到的問題:https://blog.csdn.net/Scarlett_OHara/article/details/88556798


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM