Can I get a MAC address that are connected to my site.
this code get mac address host and return error permission.
String macadress = string.Empty;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
OperationalStatus ot = nic.OperationalStatus;
if (nic.OperationalStatus == OperationalStatus.Up)
{
macadress = nic.GetPhysicalAddress().ToString();
break;
}
}
return macadress;
now how can get mac address users???
2.
how can get ip users???
Unfortunately you can't get the user's MAC address in the way that you want. It's my understanding that MAC addresses are stripped from packets when they leave your local network.
You can try to get the user's address from Request.UserHostAddress. However if you are behind a load balancer or content distribution network then you might want to try looking in Request.Headers["X-Forwarded-For"] first - this is where the users original IP address will often be written when the request is forwarded on by something.
The approach I'll usually take is to try something along the lines of:
var address = Request.Headers["X-Forwarded-For"];
if (String.IsNullOrEmpty(address))
address = Request.UserHostAddress;
The last project I worked on, we actually logged both, in case the forwarded for header had been faked.
You cannot get the MAC address from the request, however, you can get the IP with Request.UserHostAddress
You cannot get the MAC address of the end-user's machine.
You can get the user's public IP address using Request.UserHostAddress.
Note the IP address this will not be unique per-user.
If multiple users are behind the same proxy or are on a corporate network, they will usually share the same address.
You can check the X-Forwarded-For header to get a little more information.
Note that this header can be chained or faked.
public string GetMacAddress(string ipAddress)
{
string macAddress = string.Empty;
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = "arp";
pProcess.StartInfo.Arguments = "-a " + ipAddress;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length >= 8)
{
macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2)) + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6] + "-" + substrings[7] + "-" +
substrings[8].Substring(0, 2);
return macAddress;
}
else
{
return "not found";
}
}
Related
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 have a C# console application and want to be able to send an Email to a certain address if any IP addresses that are not local are found in the array, I am assuming I would use a If != statement but i cannot get anything to work. Any tips or help would be greatly appreciated.
System.Net.IPAddress[] addresslist = Dns.GetHostAddresses(C);
{
string IPs = "";
bool firstIP = true;
foreach (IPAddress ip in addresslist)
{
if (!firstIP)
{
IPs = IPs + ",";
}
IPs = IPs + ip;
firstIP = false;
}
addresslist.ToString();
if addresslist != { "10.1.20.99"} //example, have multiple IP's
then //..... this is where I am stuck
you can remove local addresses with
var filteredIPs = ipaddresslist.Where(p => !p.StartsWith("10.1"));
Then you can send a message with something like sendimportantmails(String.Join(",", filteredIPs));
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;
}
I'm coding an application that has to get the network adapters configuration on a Windows 7 machine just like it's done in the Windows network adapters configuration panel:
So far I can get pretty much all the information I need from NetworkInterface.GetAllNetworkInterfaces() EXCEPT the subnet prefix length.
I'm aware that it can be retrieved from the C++ struc PMIB_UNICASTIPADDRESS_TABLE via OnLinkPrefixLength but I'm trying to stay in .net.
I also took a look at the Win32_NetworkAdapterConfiguration WMI class but it only seems to return the IP v4 subnet mask.
I also know that some information (not the prefix length, as far as I know) are in the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters\Interfaces\{CLSID}
I also used SysInternals ProcessMon to try to get anything usefull when saving the network adapter settings but found nothing...
So, is there any clean .NET way to get this value? (getting it from the registry wouldn't be a problem)
EDIT: Gateways
This doesn't concern the actual question, but for those who need to retrieve the entire network adapter IPv6 configuration, the IPInterfaceProperties.GatewayAdresses property only supports the IPv4 gateways. As mentionned in the answer comments below, the only way to get the entire info until .NET framework 4.5 is to call WMI.
You can do so using Win32_NetworkAdapterConfiguration. You might have overlooked it.
IPSubnet will return an array of strings. Use the second value.
I didn't have time to whip up some C# code, but I'm sure you can handle it. Using WBEMTEST, I pulled this:
instance of Win32_NetworkAdapterConfiguration
{
Caption = "[00000010] Intel(R) 82579V Gigabit Network Connection";
DatabasePath = "%SystemRoot%\\System32\\drivers\\etc";
DefaultIPGateway = {"192.168.1.1"};
Description = "Intel(R) 82579V Gigabit Network Connection";
DHCPEnabled = TRUE;
DHCPLeaseExpires = "20120808052416.000000-240";
DHCPLeaseObtained = "20120807052416.000000-240";
DHCPServer = "192.168.1.1";
DNSDomainSuffixSearchOrder = {"*REDACTED*"};
DNSEnabledForWINSResolution = FALSE;
DNSHostName = "*REDACTED*";
DNSServerSearchOrder = {"192.168.1.1"};
DomainDNSRegistrationEnabled = FALSE;
FullDNSRegistrationEnabled = TRUE;
GatewayCostMetric = {0};
Index = 10;
InterfaceIndex = 12;
IPAddress = {"192.168.1.100", "fe80::d53e:b369:629a:7f95"};
IPConnectionMetric = 10;
IPEnabled = TRUE;
IPFilterSecurityEnabled = FALSE;
IPSecPermitIPProtocols = {};
IPSecPermitTCPPorts = {};
IPSecPermitUDPPorts = {};
IPSubnet = {"255.255.255.0", "64"};
MACAddress = "*REDACTED*";
ServiceName = "e1iexpress";
SettingID = "{B102679F-36AD-4D80-9D3B-D18C7B8FBF24}";
TcpipNetbiosOptions = 0;
WINSEnableLMHostsLookup = TRUE;
WINSScopeID = "";
};
IPSubnet[1] = IPv6 subnet;
Edit: Here's some code.
StringBuilder sBuilder = new StringBuilder();
ManagementObjectCollection objects = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration").Get();
foreach (ManagementObject mObject in objects)
{
string description = (string)mObject["Description"];
string[] addresses = (string[])mObject["IPAddress"];
string[] subnets = (string[])mObject["IPSubnet"];
if (addresses == null && subnets == null)
continue;
sBuilder.AppendLine(description);
sBuilder.AppendLine(string.Empty.PadRight(description.Length,'-'));
if (addresses != null)
{
sBuilder.Append("IPv4 Address: ");
sBuilder.AppendLine(addresses[0]);
if (addresses.Length > 1)
{
sBuilder.Append("IPv6 Address: ");
sBuilder.AppendLine(addresses[1]);
}
}
if (subnets != null)
{
sBuilder.Append("IPv4 Subnet: ");
sBuilder.AppendLine(subnets[0]);
if (subnets.Length > 1)
{
sBuilder.Append("IPv6 Subnet: ");
sBuilder.AppendLine(subnets[1]);
}
}
sBuilder.AppendLine();
sBuilder.AppendLine();
}
string output = sBuilder.ToString().Trim();
MessageBox.Show(output);
and some output:
Intel(R) 82579V Gigabit Network Connection
------------------------------------------
IPv4 Address: 192.168.1.100
IPv6 Address: fe80::d53e:b369:629a:7f95
IPv4 Subnet: 255.255.255.0
IPv6 Subnet: 64
Edit: I'm just going to clarify in case somebody searches for this later. The second item isn't always the IPv6 value. IPv4 can have multiple addresses and subnets. Use Integer.TryParse on the IPSubnet array value to make sure it's an IPv6 subnet and/or use the last item.
Parse the input stream of netsh with arguments:
interface ipv6 show route
Hope this helps!
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