I have a VM powered on and running in azure. I know its name but want to retrieve its IP address programmatically using the new C# SDK and avoiding the REST API. How can I do this?
Asked
Active
Viewed 2,542 times
2 Answers
1
Try this:
string subId = "deadbeef-beef-beef-beef-beefbeefbeef";
string resourceGroup = "SORG01";
string vmName = "SORG01-BOX01";
using (var client = new ComputeManagementClient(credentials))
{
client.SubscriptionId = subId;
VirtualMachine vm = VirtualMachinesOperationsExtensions.Get(client.VirtualMachines, resourceGroup, vmName);
networkName = vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/').Last();
}
using (var client = new NetworkManagementClient(credentials))
{
client.SubscriptionId = subId;
var network = NetworkInterfacesOperationsExtensions.Get(client.NetworkInterfaces, resourceGroup, vmName);
string ip = network.IpConfigurations[0].PrivateIPAddress;
}
To have these classes, you'll need to install from nuget:
- Microsoft.Azure.Management.Compute
- Microsoft.Azure.Management.Compute.Models
- Microsoft.Azure.Management.Network
Note that you'll have to select "Include Prerelease" on the nuget search window in order to find these packages. credentials
is a Microsoft.Rest.TokenCredentials
object that you acquire in this manner:
var authContext = new AuthenticationContext("https://login.windows.net/{YourTenantId}");
var credential = new ClientCredential("{YourAppID}", "{YourAppSecret}");
var result = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential);
result.Wait();
if (result.Result == null)
throw new AuthenticationException("Failed to obtain the JWT token");
credentials = new TokenCredentials(result.Result.AccessToken);

sirdank
- 3,351
- 3
- 25
- 58
-
how about the public IP address? I could not fetch the public Ip address ! – kuldeep Mar 10 '17 at 15:16
-
1@k2ibegin Check `PublicIPAddressesOperationsExtensions` rather than `NetworkInterfacesOperationsExtensions`. – sirdank Mar 10 '17 at 18:34
-
thanks , I also was able to do it via client.PublicIPAddresses.Get(groupName, publicIpName); – kuldeep Mar 13 '17 at 08:17
1
The easiest way to retrieve the public IP Address of Azure Virtual Machine is
{_VirtualMachineInstance}.GetPrimaryPublicIPAddress().IPAddress;
Very good explanation of this matter you can find here- Tom Sun answer:

JPM
- 69
- 5