Get IP Address from DNS Hostname in C#Specifically, I just needed to know what the IPv4 address was, so, I used this approach:
([System.Net.Dns]::GetHostAddresses(www.bing.com)[0]).IPAddressToString;Since there may be more than one IP Address, you need to deal with it as is appropriate in your case. Here, I just needed 1 address I could use for testing a public internet IP address. If you want to back up a step and look at the broader result set from the query, here is what you will get:
In this case, I simply took the lowest IP address (array index 0) and grabbed the IPAddressToString property. The method, .GetHostAddresses, has the following definition:[System.Net.Dns]::GetHostAddresses(www.bing.com)Address : 601988312AddressFamily : InterNetworkScopeId :IsIPv6Multicast : FalseIsIPv6LinkLocal : FalseIsIPv6SiteLocal : FalseIsIPv6Teredo : FalseIPAddressToString : 216.156.225.35Address : 551656664AddressFamily : InterNetworkScopeId :IsIPv6Multicast : FalseIsIPv6LinkLocal : FalseIsIPv6SiteLocal : FalseIsIPv6Teredo : FalseIPAddressToString : 216.156.225.32
[System.Net.Dns].GetMethod(GetHostAddresses)Name : GetHostAddressesDeclaringType : System.Net.DnsReflectedType : System.Net.DnsMemberType : MethodMetadataToken : 100671134Module : System.dllIsSecurityCritical : TrueIsSecuritySafeCritical : TrueIsSecurityTransparent : False
Courier New; font-size: 9pt;">MethodHandle : System.RuntimeMethodHandle
Attributes : PrivateScope, Public, Static, HideBySig
CallingConvention : Standard
ReturnType : System.Net.IPAddress[]
ReturnTypeCustomAttributes : System.Net.IPAddress[]
ReturnParameter : System.Net.IPAddress[]
IsGenericMethod : False
IsGenericMethodDefinition : False
ContainsGenericParameters : False
IsPublic : True
IsPrivate : False
IsFamily : False
IsAssembly : False
IsFamilyAndAssembly : False
IsFamilyOrAssembly : False
IsStatic : True
IsFinal : False
IsVirtual : False
IsHideBySig : True
IsAbstract : False
IsSpecialName : False
IsConstructor : False
And, accepts the following parameters:This quick approach allows you to drop this one line call into scripts and get IP addresses you can use quickly and easily.[System.Net.Dns].GetMethod(GetHostAddresses).GetParameters()ParameterType : System.StringName : hostNameOrAddressDefaultValue :RawDefaultValue :MetadataToken : 134226623Position : 0Attributes : NoneMember : System.Net.IPAddress[] GetHostAddresses(System.String)IsIn : FalseIsOut : FalseIsLcid : FalseIsRetval : FalseIsOptional : False