简体   繁体   中英

Current IP address in use

I have a C# Win 7 desktop application that sends web requests using HttpClient . Is there any way to find out which network adapter or NetworkInterface is used to send these requests? (There could be multiple LAN, WAN and virtual adapters.)

I don't really want to use TcpClient, UdpClient or any socket level program as it more low level and user may decide to block the ports.
One route I am trying to pursue is to find IP address of the current request and then try to match it with the IP address from the NetworkInterface (using NetworkInterface.GetAllNetworkInterfaces ), but HttpClient don't tell you your IP that is used to send the requests.

This is what I ended up doing:

IPAddress localAddr = null;
try
{
    using (UdpClient udpClient = new UdpClient("8.8.8.8", 0)) //connect to google dns
    {
        localAddr = ((IPEndPoint)udpClient.Client.LocalEndPoint).Address;
        udpClient.Client.Close();
        udpClient.Close();
    }
}
catch (SocketException sex)
{
    Console.WriteLine("Failed to make UDP connection, no connection to DNS ? ");
}
//find all network interfaces
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface activeAdapter = null;
foreach (NetworkInterface adapter in nics.Where(n => n.OperationalStatus == OperationalStatus.Up))
{
    //wifi adapter will be 'up' only if its associated with a hotspot
    IPInterfaceProperties properties = adapter.GetIPProperties();
    var match = properties.UnicastAddresses.Any(a => a.Address.Equals(localAddr));
    if (match)
    {
        activeAdapter = adapter;
        break;
    }
}

I had to rely on UDP client, can't find a way to get ip from HttpClient

This will get you the current 'active' network adapter that is being used to connect to internet.

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