How can you dynamically get the IP address of the server (PC which you want to connect to)?
Asked
Active
Viewed 9,706 times
15
-
As an example, Ping.Send requires an IPAddress, so for "server is alive" validation code it needs translation. – Dirk Bester Aug 19 '14 at 18:35
5 Answers
10
IPHostEntry Host = Dns.GetHostEntry(DNSNameString);
DoSomethingWith(Host.AddressList);

chaos
- 122,029
- 33
- 303
- 309
-
Thanks guys for your help but I want to get the visitor's IP address not the pc im working on – Jun 22 '09 at 23:11
-
3Erm. My example is nothing to do with the PC you're on. DNSNameString is meant to be the name of the server you're connecting to -- that is, answering the original question. I don't know where this stuff you're saying about a visitor's IP address comes from or what it has to do with the question. – chaos Jun 22 '09 at 23:21
2
If you Use the Below Method you will be able to resolve correctly
public static bool GetResolvedConnecionIPAddress(string serverNameOrURL, out IPAddress resolvedIPAddress)
{
bool isResolved = false;
IPHostEntry hostEntry = null;
IPAddress resolvIP = null;
try
{
if (!IPAddress.TryParse(serverNameOrURL, out resolvIP))
{
hostEntry = Dns.GetHostEntry(serverNameOrURL);
if (hostEntry != null && hostEntry.AddressList != null && hostEntry.AddressList.Length > 0)
{
if (hostEntry.AddressList.Length == 1)
{
resolvIP = hostEntry.AddressList[0];
isResolved = true;
}
else
{
foreach (IPAddress var in hostEntry.AddressList)
{
if (var.AddressFamily == AddressFamily.InterNetwork)
{
resolvIP = var;
isResolved = true;
break;
}
}
}
}
}
else
{
isResolved = true;
}
}
catch (Exception ex)
{
}
finally
{
resolvedIPAddress = resolvIP;
}
return isResolved;
}

Tyronne Thomas
- 41
- 1
0
You want to do an nslookup.
Here's an example:
http://www.c-sharpcorner.com/UploadFile/DougBell/NSLookUpDB00112052005013753AM/NSLookUpDB001.aspx

Chris Harris
- 4,705
- 3
- 24
- 22
0
Based on your comment on chaos's answer, you don't want the IP address of a server, you want the IP address of a client. If that's the case, fix your question ... and your answer would be HttpRequest.UserHostAddress.

Richard Anthony Hein
- 10,550
- 3
- 42
- 62