How do I get a user's IP address with .NET code? I'm using Foo Basic Web Studio IDE that uses ASP.net code.
3 Answers
string strHostName = HttpContext.Current.Request.UserHostAddress.ToString();
string IPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
3 Comments
MrPaulch
Parhaps using
System.Net.Dns.GetHostName to retreive the host name would be more straight forward? No need for the HttpContextSailesh Babu Doppalapudi
Yes. We get either way @MrPaulch. Thanks for your suggestion.
David Makogon
@MrPaulch - you should post that as a separate answer, for voting purposes. Lets the OP decide which is the best answer to accept. Can't do that with a comment.
Here is another way of doing it:
' Get your Hostname
Dim szHost As String = System.Net.Dns.GetHostName()
' Get the host entry for said hostname
Dim hostEntry As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(szHost)
' To get the ip address of the first available net interface:
Dim ip As System.Net.IPAddress = New System.Net.IPAddress(hostEntry.AddressList(0).GetAddressBytes)
Note that hostEntry contains the AddressList array, listing the IP-Addresses of all active network interfaces.
So you might want to check/filter them for relevance.
2 Comments
Matt Wilko
This will retrieve the server IP not the remote client IP. You need to use
HttpRequest.UserHostAddress as pointed out in the other answerMrPaulch
Oh this is awkward. I thought the OP meant the 'user' of the server aplication though. (He never even wrote the word 'client')