HttpContext IP Problem - c#

I have a problem when I use HttpContext.Current.Request.UserHostAddress, some times returns "192.168.0.17" (IPv4) and some times returns "fe80::99be:a05d:7938:1c30%8" (IPv6), calling from the same computer and navigator.
What I do to return always IPv4?

Check out this post on 4GuysFromRolla and see if it helps at all. I think this is the information you're looking for.
https://web.archive.org/web/20201028122055/https://aspnet.4guysfromrolla.com/articles/071807-1.aspx
~md5sum~
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != String.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}

Found a solution that somebody hacked up. Can't say if it'll work, tho =)
http://www.eggheadcafe.com/software/aspnet/30078410/request-object.aspx

Related

NetworkInfo.Type is obsolete:"deprecated"

For example i have this method:
public static bool IsConnectedMobile
{
get
{
var info = ConnectivityManagers.ActiveNetworkInfo;
return info != null && info.IsConnected && info.Type == ConnectivityType.Mobile;
}
}
and i get an error here: info.Type == ConnectivityType.Mobile;
And my question is, can i found an alternative? (without using other libraries)
ActiveNetworkInfo you need get it from GetSystemService Just use this code
ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);
NetworkInfo activeNetwork = cm.ActiveNetworkInfo;
if (activeNetwork != null)
{
//connected to the internet
}
else
{
//not connected to the internet
}
& for more information go through this thread
This feature is platform-specific. Basically you can check the Network Connection status by using the below code:
var cm = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
bool isConnected = cm.ActiveNetworkInfo.IsConnected;
Should be quite straightforward.
Thanks.

Why does getting an IP address throw an exception?

Background:
My program starts up and it must obtain the IP address of the machine it is running on.
It is the "server" in a client-server architecture that receives incoming tcp-ip messages.
I should also add the machine :
Has multi-ip addresses available
Is running Windows 2008 R2 Server
Here is the code that obtains the IP address:
public bool IsNetworkAvailable
{
get
{
return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
}
public string thisIP { get; private set; }
public void GetThisIP()
{
if (!string.IsNullOrEmpty(thisIP))
{
return;
}
thisIP = "*";
if (IsNetworkAvailable)
{
using (System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(
System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Dgram, 0))
{
socket.Connect("11.0.1.5", 65530);
System.Net.IPEndPoint endPoint = socket.LocalEndPoint as System.Net.IPEndPoint;
thisIP = endPoint.Address.ToString();
}
}
}
Here is the error message:
(0x80004005): A socket operation was attempted to an unreachable network 11.0.1.5:65530
at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)
SOLUTION:
I have changed my code to what rodcesar.santos suggested in this:
Get local IP address
here is my (modified) code (and it works)
System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
{
continue;
}
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
{
continue;
}
if (mostSuitableIp != null)
{
break;
}
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
{
continue;
}
if (System.Net.IPAddress.IsLoopback(address.Address))
{
continue;
}
if (mostSuitableIp == null && address.IsDnsEligible)
{
mostSuitableIp = address;
break;
}
}
}
thisIP = mostSuitableIp != null ? mostSuitableIp.Address.ToString() : "";
After reading the accepted answer # A socket operation was attempted to an unreachable host,
I assume that the specific client-computer than receives this error has a somewhat faulty network.
Quoting #Stephen Cleary
This error indicates that the network was not connected or not configured correctly. It is definitely an error on the client machine, not your server.
There isn't much you can do to "solve" the problem. Pretty much all you can do is upgrade the client's network drivers and check for connection problems (maybe they're barely within wireless range, or the Ethernet cable is missing its locking tab).
System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
{
continue;
}
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
{
continue;
}
if (mostSuitableIp != null)
{
break;
}
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
{
continue;
}
if (System.Net.IPAddress.IsLoopback(address.Address))
{
continue;
}
if (mostSuitableIp == null && address.IsDnsEligible)
{
mostSuitableIp = address;
break;
}
}
}
thisIP = mostSuitableIp != null ? mostSuitableIp.Address.ToString() : "";

How to obtain Public IP of a device using C# with out using external API/Services

public static string GetPublicIp()
{
HttpContext context = 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"];
}
I'm trying to get the client Public IP but the above code only returns the client Local IP. If different people are connecting to my organisation from the same organisations network, i want to get only their public IP address. I'm not intrested in their local IPs, is this possible.
Below is one solution i have so far seen but i'm NOT liking it.
public static string GetPublicIp()
{
string direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
using (WebResponse response1 = request.GetResponse())
using (StreamReader stream1 = new StreamReader(response1.GetResponseStream()))
{
direction = stream1.ReadToEnd();
}
//Search for the ip in the html
int first1 = direction.IndexOf("Address: ") + 9;
int last1 = direction.LastIndexOf("</body>");
direction = direction.Substring(first1, last1 - first1);
return direction;
}
The above sample solution can get me the public IP but i don't want to be tied to an external service that i have no control over because if that service is down then iam screwed and the performance is terrible.
Does any one know how i can get the clients public IP with out calling external services?
This method gives you the local ip address. I've copied it from a WinRT-Solution, maybe the class names are a bit different in other .NET environments.
private static string GetLocalAddress()
{
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
return hn.DisplayName;
}
}
return IpAddress.Broadcast.Address;
}
EDIT: The following method prints out all local ip addresses.
private static void PrintLocalAddresses()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var ni in interfaces)
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
{
var adapterProperties = ni.GetIPProperties();
foreach (var x in adapterProperties.UnicastAddresses)
{
if (x.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine(x.Address);
}
}
}
}
}

WMI reports non-unique processor id, hard drive id and mac address

We have the following code to retrive the harddrive id processor id and mac address:
private static string GetWMIValue(string query, string propertyName)
{
try
{
using (ManagementObjectSearcher search = new ManagementObjectSearcher(query))
{
using (ManagementObjectCollection results = search.Get())
{
foreach (var result in results)
{
if (result != null && result[propertyName] != null)
{
return result[propertyName].ToString();
}
}
}
}
}
catch
{
// do nothing.
}
return null;
}
public static string GetHardDriveSerialNumber()
{
string driveLetterName = Assembly.GetExecutingAssembly().Location.Substring(0, 1);
return GetWMIValue("SELECT VolumeSerialNumber FROM Win32_LogicalDisk WHERE DeviceID=\"" + driveLetterName + ":\"", "VolumeSerialNumber");
}
public static string GetProcessorId()
{
return GetWMIValue("SELECT ProcessorId FROM Win32_Processor", "ProcessorId");
}
public static string GetMacAddress()
{
return GetWMIValue("SELECT MacAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE", "MacAddress");
}
This works fine EXCEPT on one particular brand of tablet (as far as we know). On this brand, every machine has the same 3 values. As you can imagine, this screws with our licensing somewhat.
Has anyone ever seen this or does anyone have a better more reliable mechanism?
Thanks
After a bit more research it appears as though this is a well know and talked about issue. I need to do some work...
Thankfully, this wasn't my mess :) I just have to fix it :(

In C#, how do I resolve the IP address of a host?

How can you dynamically get the IP address of the server (PC which you want to connect to)?
System.Dns.GetHostEntry can be used to resolve a name to an IP address.
IPHostEntry Host = Dns.GetHostEntry(DNSNameString);
DoSomethingWith(Host.AddressList);
If you Use the Below Method you will be able to resolve correctly
public static bool GetResolvedConnecionIPAddress(string serverNameOrURL, out IPAddress resolvedIPAddress)
{
bool isResolved = false;
IPHostEntry hostEntry = null;
IPAddress resolvIP = null;
try
{
if (!IPAddress.TryParse(serverNameOrURL, out resolvIP))
{
hostEntry = Dns.GetHostEntry(serverNameOrURL);
if (hostEntry != null && hostEntry.AddressList != null && hostEntry.AddressList.Length > 0)
{
if (hostEntry.AddressList.Length == 1)
{
resolvIP = hostEntry.AddressList[0];
isResolved = true;
}
else
{
foreach (IPAddress var in hostEntry.AddressList)
{
if (var.AddressFamily == AddressFamily.InterNetwork)
{
resolvIP = var;
isResolved = true;
break;
}
}
}
}
}
else
{
isResolved = true;
}
}
catch (Exception ex)
{
}
finally
{
resolvedIPAddress = resolvIP;
}
return isResolved;
}
You want to do an nslookup.
Here's an example:
http://www.c-sharpcorner.com/UploadFile/DougBell/NSLookUpDB00112052005013753AM/NSLookUpDB001.aspx
Based on your comment on chaos's answer, you don't want the IP address of a server, you want the IP address of a client. If that's the case, fix your question ... and your answer would be HttpRequest.UserHostAddress.

Categories