1

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 3

1
string strHostName = HttpContext.Current.Request.UserHostAddress.ToString();
string IPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
Sign up to request clarification or add additional context in comments.

3 Comments

Parhaps using System.Net.Dns.GetHostName to retreive the host name would be more straight forward? No need for the HttpContext
Yes. We get either way @MrPaulch. Thanks for your suggestion.
@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.
0

Here is the way you can that IP address of users.

string clientIp = Request.ServerVariables("HTTP_X_FORWARDED_FOR");

if(string.IsNullOrEmpty(clientIp))
       clientIp = Request.ServerVariables("REMOTE_ADDR")

Comments

0

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

This will retrieve the server IP not the remote client IP. You need to use HttpRequest.UserHostAddress as pointed out in the other answer
Oh this is awkward. I thought the OP meant the 'user' of the server aplication though. (He never even wrote the word 'client')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.