官方文檔:https://docs.microsoft.com/zh-cn/dotnet/api/system.net.servicepoint.bindipendpointdelegate
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