Brian Rice
Brian Rice

Reputation: 3257

Identify individual Azure app service machines (especially behind a load balancer)

I want to identify individual Azure app service machines so that I can record info in a database. I was thinking I would use the local ip address of the machine using the function below but I get an empty string returned back. The code works for VM's but not for app services. Any thoughts (especially if these are eventually behind a load balancer and running identical code. (any string is ok... it doesn't have to be an ip address)

    public static string GetLocalIpAddress()
    {
        UnicastIPAddressInformation mostSuitableIp = null;
        var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        foreach (var network in networkInterfaces)
        {
            if (network.OperationalStatus != OperationalStatus.Up)
                continue;

            var properties = network.GetIPProperties();
            if (properties.GatewayAddresses.Count == 0)
                continue;

            foreach (var address in properties.UnicastAddresses)
            {
                if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                    continue;

                if (IPAddress.IsLoopback(address.Address))
                    continue;

                if (!address.IsDnsEligible)
                {
                    if (mostSuitableIp == null)
                        mostSuitableIp = address;
                    continue;
                }

                // The best IP is the IP got from DHCP server  
                if (address.PrefixOrigin != PrefixOrigin.Dhcp)
                {
                    if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
                        mostSuitableIp = address;
                    continue;
                }
                return address.Address.ToString();
            }
        }
        return mostSuitableIp != null
            ? mostSuitableIp.Address.ToString()
            : "";
    }

Upvotes: 0

Views: 56

Answers (0)

Related Questions