Please correct me if i am wrong. There are two types of IP -
One, the static(fixed) IP address we assign to the LAN card and second that we received from the service provider.
For ex. The IP address set for my machine is 192.168.1.10 while the IP address given by ISP is 218.64.xx.xx. (You can check this using http://www.ip2location.com/)
When I use ASP.net, i can get the IP address provided by ISP using -
HttpContext.Current.Request.UserHostAddress;
The Problem:
Now, I am working in Windows Forms environment but unable to get the IP provided by ISP, though I am able to get the fixed IP.
Can anybody help me?
Thanks for sharing your time.
You're trying to get the external IP address of your router.
You need to send an HTTP request to a third-party service which will reply with the IP address.
You can do that using the WebClient class.
For example:
///<summary>Gets the computer's external IP address from the internet.</summary>
static IPAddress GetExternalAddress() {
//<html><head><title>Current IP Check</title></head><body>Current IP Address: 129.98.193.226</body></html>
var html = new WebClient().DownloadString("http://checkip.dyndns.com/");
var ipStart = html.IndexOf(": ", StringComparison.OrdinalIgnoreCase) + 2;
return IPAddress.Parse(html.Substring(ipStart, html.IndexOf("</", ipStart, StringComparison.OrdinalIgnoreCase) - ipStart));
}
The terminology is wrong; your machine has a private IP and a public IP (not "static" and "dynamic").
To get the public IP, you need to bounce off a public server, e.g., whatismyip.org or your own server.
i found manu methods one of them is a html request to http://whatismyip.com
public static IPAddress GetExternalIp()
{
string whatIsMyIp = "http://whatismyip.com";
string getIpRegex = #"(?<=<TITLE>.*)\d*\.\d*\.\d*\.\d*(?=</TITLE>)";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
string requestHtml = "";
try
{
requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
}
catch (WebException we)
{
// do something with exception
Console.Write(we.ToString());
}
Regex r = new Regex(getIpRegex);
Match m = r.Match(requestHtml);
IPAddress externalIp = null;
if (m.Success)
{
externalIp = IPAddress.Parse(m.Value);
}
return externalIp;
}
or use
IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
Console.Write(IPHost.AddressList[0].ToString());
you can try this in the System.Net namespace:
Dns.GetHostAddresses(Dns.GetHostName())
try with this (using System.Net):
IPHostEntry he = Dns.GetHostByName(Dns.GetHostName());
var s = he.AddressList[0].ToString(); // returns IP address
Related
I have searched and read almost every article related to my search about how to get client ipaddress and machine name but all the codes return only server ip and name. I've tried these codes also given below, it gives my PC ip on localhost but on the server, it gives server ip and name :
string stringHostName = Dns.GetHostName();
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
and also used this method :
public string GetUserIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDER_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}enter code here
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
It gives ::1 on localhost but on the server it gives server ip only.
Kindly help me if there any way possible to get client ipaddress and machine name using C#.
I've actually deployed my asp website on IIS and everything works well. I have done some reading on how to bypass the proxy server but i'm still unsure on how to do it. The reason why i want to bypass the proxy server on the network is to be able to read client's ip address (the ip address behind the proxy). Frankly speaking, i don't have much knowledge on this topic..
I read from MSDN that you can add in lines of codes into Web.Config file to bypass the proxy server. But i'm not sure what to type in or how to use this defaultproxy tag.
Link
Right now i'm only retrieving either 127.0.0.1 which is localhost or the machine's network external ip address which is not what i want..
Anyone can point me in the right direction to getting ip address behind the proxy? Appreciate any help please. Thank you..
Codes i have been experimenting to get client's IP address:
protected void getIP_Click(object sender, EventArgs e)
{
String hostName = System.Net.Dns.GetHostName();
String clientIpAddressHostName = System.Net.Dns.GetHostAddresses(hostName).GetValue(0).ToString();
IP1.Text = clientIpAddressHostName;
String clientIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_HOST"].ToString();
IP2.Text = clientIpAddress;
String ip = null;
if (String.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
IP3.Text = ip;
String ipNext = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
IP4.Text = ipNext;
//String ipNextNext = HttpContext.Current.Request.UserHostAddress;
String ipNextNext = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString();
IP5.Text = ipNextNext;
String last = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
IP6.Text = last;
Label2.Text = getIPAdd();
try
{
String externalIP;
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
Label1.Text = externalIP;
}
catch (Exception ex)
{
logManager log = new logManager();
log.addLog("IP Add", "IP Add", ex);
}
}
private String getIPAdd()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
Results,
Requested Details:
I just used this to get the client IP address:
HttpContext.Current.Request.UserHostAddress
As I can see you have that one in your code too, but it's commented out.
It worked for me:
I am running an ASP.NET MVC app in the localhost - dev server given with a Visual Studio. I want to get the IP address. I tried
Request.UserHostAddress
and
Request.ServerVariables("REMOTE_ADDR")
In both cases, I am getting::1 as a result. What is it? Why am I getting it? How can I get 127.0.0.1 or 192.168.1.xxx?
You are getting a valid IP Address; ::1 is localhost for IPv6.
What you're seeing when calling 'localhost' is valid. ::1 is the IPv6 loopback address. Equivalent to 127.0.0.1 for IPv4.
Instead of calling:
http://localhost/...
Call:
http://{machinename}/...
or
http://127.0.0.1/...
or
http://192.168.1.XXX/...
[Replace {machinename} with your machine's computer name. Replace XXX with your computer's IP address.]
Anyone calling into your machine to the MVC app will have their valid IP address as a result. If the client is an IPv6 host it will save their IPv6 IP address. If the client is an IPv4 host it will save their IPv4 IP address.
If you always want to save an IPv4 address take a look at this article on how they accomplished it with a simple class https://web.archive.org/web/20211020102847/https://www.4guysfromrolla.com/articles/071807-1.aspx. You should be able to take their example and build a quick helper method to accomplish this.
Request.Params["REMOTE_ADDR"]
instead of Request.ServerVariables("REMOTE_ADDR")
If you want localhost return 127.0.0.1, maybe you need to change your "hosts" file.
You can find it in "%systemdrive%\Windows\System32\drivers\etc"
It works for me, now I get 127.0.0.1 with "Request.ServerVariables["REMOTE_ADDR"]". I uncomment 127.0.0.1 (remove #).
Here you can find default hosts file
http://support.microsoft.com/kb/972034
My file
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
# ::1 localhost
below code i have used for finding ip
public static string GetIp()
{
var Request = HttpContext.Current.Request;
try
{
Console.WriteLine(string.Join("|", new List<object> {
Request.UserHostAddress,
Request.Headers["X-Forwarded-For"],
Request.Headers["REMOTE_ADDR"]
})
);
var ip = Request.UserHostAddress;
if (Request.Headers["X-Forwarded-For"] != null)
{
ip = Request.Headers["X-Forwarded-For"];
Console.WriteLine(ip + "|X-Forwarded-For");
}
else if (Request.Headers["REMOTE_ADDR"] != null)
{
ip = Request.Headers["REMOTE_ADDR"];
Console.WriteLine(ip + "|REMOTE_ADDR");
}
return ip;
}
catch (Exception ex)
{
Log.WriteInfo("Message :" + ex.Message + "<br/>" + Environment.NewLine +
"StackTrace :" + ex.StackTrace);
}
return null;
}
If you get ipv6 address , after that you can find it valid ipv4 address map for ipv6 address.
c # code is below;
public static string GetIP4Address(string ip) {
try {
var hostNames = Dns.GetHostEntry(ip);
var ipv4 = hostNames.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
if(ipv4 != null) {
return ipv4.ToString();
}
} catch(Exception ex) {
log.WarnFormat("Error When Getting Client Ipv4");
}
return ip;
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
how to get my own IP address in C#?
how to get ip address of machine in c#
Hi all, I am currently developing a c# application for windows using WPF. I would like to get the computers external IP address i.e. the internet address not the local computer ip address or the local router address.
Thanks for your help.
Like stated earlier, you need an external web server. An easy call to HTTP GET with the URL "http://checkip.dyndns.org/" will get you a simple text string with your IP.
You need to have a web server sitting somewhere in the cloud so that you can call and that will be able to give you your external IP address.
Looks like this one is free.
[EDIT]
A simple request to here will get you your ip.
This is a way to get any network address (not necessarily the internet ip) as pointed out in the comments:
IPAddress host = IPAddress.None;
foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
{
host = ip;
if (ip.AddressFamily == AddressFamily.InterNetwork)
break;
}
The only way I have found is to do a httpWebRequest to http://www.whatismyip.com/automation/n09230945.asp and parse the results for the ip
You can try connecting to whatismyip.com, as shown in the code below:
using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace DreamInCode.Snippets
{
public class IpFinder
{
public static IPAddress GetExternalIp()
{
string whatIsMyIp = "http://whatismyip.com";
string getIpRegex = #"(?<=<TITLE>.*)\d*\.\d*\.\d*\.\d*(?=</TITLE>)";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
string requestHtml = "";
try
{
requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
}
catch (WebException we)
{
// do something with exception
Console.Write(we.ToString());
}
Regex r = new Regex(getIpRegex);
Match m = r.Match(requestHtml);
IPAddress externalIp = null;
if (m.Success)
{
externalIp = IPAddress.Parse(m.Value);
}
return externalIp;
}
}
}
NOTE: The code comes from this post http://www.dreamincode.net/forums/topic/24692-showing-the-external-ip-address-in-c%23/ .
Is there a 1 line method to get the IP Address of the server?
Thanks
Request.ServerVariables["LOCAL_ADDR"];
From the docs:
Returns the server address on which the request came in. This is important on computers where there can be multiple IP addresses bound to the computer, and you want to find out which address the request used.
This is distinct from the Remote addresses which relate to the client machine.
From searching the net I found following code: (I couldn't find a single line method there)
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[index].ToString();
// Show the IP
MessageBox.Show(myIP);
-> where index is the index of your ip address host (ie. network connection).
Code from: http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html
As other(s) have posted, System.Net.Dns.GetHostEntry is the way to go. When you access the AddressList property, you'll want to take the AddressFamily property into account, as it could return both IPv4 AND IPv6 results.
This method will return your machine public IP address when run this code on your PC and when you deploy your application on server will return Server IP address.
public static string Getpublicip()
{
try
{
string externalIP = "";
var request = (HttpWebRequest)WebRequest.Create("http://icanhazip.com.ipaddress.com/");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
externalIP = new WebClient().DownloadString("http://icanhazip.com");
return externalIP;
}
catch (Exception e)
{
return "null";
}
}