Get the public IP address of a client - c#

I'm creating a web application where I need a functionality that if someone client log in to my website the client's public IP address must be logged. I have some javascript to do this but some of my pal not agree to use a javascript library reason they don't trust it. Such as http://l2.io/ip.js?var=myip as mentioned here
So we need all of it as server side code. So i found few more code in this
link but unfortunately I'm not getting the expected result (it only returns local hosts IP). Could anyone help me to solve this please.
I have tried the bellow code
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
but this is not providing me the public IP. Do I need to deploy it or something.

HttpContext.Current.Request.UserHostAddress
This should get the public IP address of a client
EDIT
So you're after the IP address of your own machine as the rest of the world sees it??
This only really matters if you're hosting in on lets say an Intranet where the clients will be on the same network and thats the only address you will get if you use HttpContext.Current.Request.UserHostAddress. You will need to use a lookup api or something in this case. But then you'd know the external IP of your network!
If this is to be hosted on the internet then HttpContext.Current.Request.UserHostAddress will work just fine as every client will be displaying it's external IP.
It's showing 127.0.0.1 I'm guessing because you're testing on your local machine and this will be it's loopback address.
Hope this helps

Related

How to access web service on ServiceStack from android device?

I have an android application that's supposed to send a request to a simple HelloWorld C# webservice I made on ServiceStack but I am not able to connect. My application crashes when I try to connect. Here is my code on Eclipse, trying to access the ServiceStack service:
String base = "http://192.168.1.7:62938/json/reply/Hello?Name=";
String str = editTextField.getText().toString();
StringBuilder url = new StringBuilder(base + str);
String result = "";
HttpClient hc = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url.toString());
HttpResponse r = hc.execute(httpget);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject o = new JSONObject(data);
result= o.getString("result");
}
My C# service code for ServiceStack:
//Request DTO
public class Hello
{
public string Name { get; set; }
}
//Response DTO
public class HelloResponse
{
public string Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
//Can be called via any endpoint or format, see: //http://mono.servicestack.net/ServiceStack.Hello/
public class HelloService : Service
{
public object Any(Hello request)
{
return new HelloResponse { Result = "Helloooo, " + request.Name };
}
}
My service works fine on my laptop when I go to localhost:62938/json/reply/Hello?Name="arbitraryName"
but it does not work when I try to replace localhost with my laptop's ip address and access the service from an android device. It also does not work if I replace localhost with my IP address and try it on my browser on my laptop. Note: I want to make it work from a real android device, not an emulator.
Is there something different with ServiceStack services where I cannot access it normally from another device? I have already tried opening port 62938 and it did not work.
I appreciate any guidance. Thank you.
It also does not work if I replace localhost with my IP address and try it on my browser on my laptop.
If you have tried accessing the ServiceStack service through the local IP address of 192.168.1.7 in your computer's web browser and it is also unreachable, then the issue isn't isolated to Android.
This is issue is likely the result of one or more of these problems:
Check you are listening on the correct IPs:
Your ServiceStack service isn't configured to listen for requests on any other interfaces other than localhost. Select your relevant hosting option:
Self Hosting:
This can happen if you are self hosting and you have configure the app host to start with appHost.Start("http://localhost:62938/");. You would need to replace localhost with a + symbol to have it listen on all local addresses.
IIS Express:
By default IIS Express is used by Visual Studio during development, unless manually configured to use IIS, and is restricted to localhost requests only. You should see this answer as to how to configure IIS Express to allow non-local access as well.
This tutorial by Scott Hanselman is also very good, and provides great step-by-step instructions for configuring IIS Express.
IIS:
You can confirm the IP addresses that you server is configure to listen on by following these instructions. They provide instructions for both IIS6 and IIS7+.
Firewall:
Your computer may have a firewall preventing you accessing that port, or accepting outside traffic. Note your firewall may be built into antivirus software you run. You should add an exception rule for http traffic on port 62938.
Correct IP:
You are trying to access on 192.168.1.7. You should confirm that IP address is in fact correct. Most home networks are configured to provide a dynamic IP address by the network router. The IP address may have changed since you last checked it. You should try running a ping to the IP from your development machine.
Until you can successfully access the service through your web browser on your development machine, at the local network IP starting 192.168.1.X then I wouldn't attempt to access from Android. It's not an Android issue if other systems can't access your service also.
I hope that helps. If you provide more information about your specific environment, I may be able to provide more specific instructions. If I had to guess, I would say IIS Express issue.
Edit:
Now that you can access the service in the web browser of your android device but not in the application, we know the service is remotely accessible. This means your connectivity issue is isolated now to your application. The first thing I would check, is that your application has permission to make network requests. In your AndroidManifest.xml you need to ensure that android.permission.INTERNET is included
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
If you have that permission then you should be able to make the request successfully. If it continues to fail, then the reason need to be diagnosed from the exception that is causing the application to crash. In which case you should wrap the data request in a try { ... } catch(Exception exception) { } and log the exception.
As the Android emulator is considered to be running on a different device, to refer to the loopback IP (127.0.0.1) on our local development machine we need to use the special 10.0.2.2 alias.
Other special device IP's can be found in Andorid's documentation.

How to get network ip address in internet dotted-integer format in c# winforms

I am trying to get Network IP Address as http://checkip.dyndns.org/ returns.
but i am getting this result from follwoing code.
fe80::28d3:b8e8:caab:63b3%10
i want ip address in internet dot-integer format lilke 122.168.149.143
foreach (IPAddress ipa in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{
textBox2.Text = ipa.ToString();
break;
}
}
You are currently filtering by IPv6 addresses when you mean to be filtering by IPv4 addresses! This is why IPAddress.ToString() is returning the IP in colon-hexadecimal notation.
To filter by IPv4 addresses you will need to filter according to AddressFamily.InterNetwork instead:
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{ }
It is my understanding that you would like to obtain your public address. The code you listed will return your private (local) address!
The Windows Operating system does not care about your public IP. The Operating System simply routes out to the defined gateway and doesn't worry about the details. The only way to resolve your public IP is to query some external system. You need external help.
The most reliable way to obtain your public address is to connect to an external web server that can resolve and output your public address in plain-text. You already listed a suitable service with your question. You can even take responsibility for the service by providing the service yourself. The PHP code to achieve this is very simple.
If your router supports UPnP (or SNMP) you could query your router, although, this might not work. This might suffice for YOUR machine but some routers do not support UPnP and security conscious users may very well have disabled UPnP due to security holes. See this SO question for a managed UpNp library.
I have read that you can use tracert to an established website (one you know will be online) and the first "hop" will be to your route. I have never tried this.
The dot-integer format can be used only for IP ver. 4 addresses.
In the code sample you even explicitly select only IP ver. 6 addresses.
Use AddressFamily.InterNetwork instead of AddressFamily.InterNetworkV6 to select IPv4 address, then ToString will format it in the way you expect.

How do I get the local host IP address in a Windows Store app?

A particular rest service I am calling in a Windows Store app wants the IP address of the calling computer as a parameter. None of the tried and true examples using System.Net or System.Net.NetworkInformation compile in a Store app.
What is the magical combination of types and methods available in a windows store app that will get to the local machine's IP address? I feel like it is probably obvious but I am not seeing it!
You will have to contact an external server. Even if the platform supplies an API to retrieve the network address, the host could still be located behind a proxy or a NAT (and you will see something like 192.168.1.4, instead of your external IP address).
Just perform an HTTP request towards services like http://ifconfig.me/ or http://whatismyip.com/ and parse the IP.
Local network IP address:
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
// E.g.: 192.168.1.108
Debug.WriteLine(localHostName);
}
}
}

C# - How to get IP Address when connected to (RAS) VPN

Good afternoon,
Can anyone give any examples of how to obtain the IP Address of the local machine when it's connected to a remote windows domain network via VPN (RAS)? i.e. I need the VPN address and not the remote users local network address.
For example, my Server Side Windows Service communicates with my client side application and needs to create a log of all connected users and their IP Addresses.
This solution is easy enough when using a computer on the local network, but I wondered how I can go about getting the IP addresses of the users who are connected to the server via VPN. Please note that the IP address get method will be executed client side and sent to the server.
Here's my current code that works only when locally connected to the domain network:
public static string GetLocalIPv4()
{
string ipv4Address = String.Empty;
foreach (IPAddress currrentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (currrentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
{
ipv4Address = currrentIPAddress.ToString();
break;
}
}
return ipv4Address;
}
Our internal network is controlled by Windows SBS and uses a domain such as mycompany.local.
Thank you very much for your time and I look forward to reading your responses.
Rob
As the comment from #MarcB notes, cannot think of a good reason why you might want that info... so would be interesting if you could explain a use for this in an application just out of curiosity.
However, there are a lot of incorrect answers on here and online regarding enumerating IP addresses for a machine by using Dns.GetHostAddresses. It appears most people are not realizing the difference between looking up a machine name in the configured DNS resolver versus enumerating the machine address. These are very different things and while it might seem to return the right results in many cases, this is absolutely the wrong way to go about it because they are not the same thing. For example, see this link to an article on here where the original poster flagged an incorrect response as the answer but the correct response is below by #StephanCleary. See:
Get IPv4 Addresses
The difference is you want to look at the machines configuration and enumerate whatever IP address you are interested in locating from the machines own TCPIP stack. The code above and many of the incorrect responses try to lookup the name in the DNS resolver. Once you have that part correct, then you should be able to determine the VPN connection based on the network adaptor (by name or other attribute).

How can i get IP Address of my 3G modem?

My GPRS modem has got a sim card. it can connect Web. Web service give it a ip number. i need it. like that: http://www.your-ip-address.com/
How can i do that C#?
You can use the static method WebClient.DownloadString(url) to read your external IP address from any web service providing such data:
string ip = System.Net.WebClient.DownloadString("http://whatismyip.org/");
If you are going to use this in a production environment, better make sure that the URL you are pointing to, is guaranteed to stay around for the entire lifespan of your application. The best way is probably to host the web service yourself.
Also, you should add some error checking around this code, as it will fail if the internet connection or the web service is unavailable.
You can get a list of your IP addresses via DNS using the following code:
var name = Dns.GetHostName();
var entry = Dns.GetHostEntry(name);
foreach (var address in entry.AddressList) {
Console.WriteLine(address);
}
If you want the IP address as a property of the hardware, you can use the System.Management.ManagementClass with the name Win32_NetworkAdapterConfiguration. See http://msdn.microsoft.com/en-us/library/system.management.managementclass.aspx for details.
You can create a WebRequest to http://whatismyip.com/automation/n09230945.asp which houses only your IP address
Start here

Categories

Resources