I want to find the ip that my computer connects to the internet correctly.I have questions about a few things I have tried.
Firstly :
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null && ni.OperationalStatus == OperationalStatus.Up) {
switch (ni.NetworkInterfaceType) {
case NetworkInterfaceType.Wireless80211:
case NetworkInterfaceType.Ethernet:
{
foreach(UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) {
if (ip.Address.AddressFamily == AddressFamily.InterNetwork) {
return ip.Address.ToString();
}
}
break;
}
}
}
}
When I tried the code above, if my computer has a virtual adapter installed (for example vpn), the vpn adapter is also detected as ethernet and operational status up. When I run vpn, there are two strings ip like (192.168.1.24 and 25.25.1.150).
As a result of this error, I decided to find the name of my computer and ping it and find a rope with the returned result.
like the code below:
int timeout = 10000;
Ping ping = new Ping();
try {
PingReply pingreply = ping.Send(Environment.MachineName.ToString(), timeout);
if (pingreply.Status == IPStatus.Success) {
return pingreply.Address.ToString();
}
}
catch(Exception ex) {
LogHelper.WriteErrorLog(ex);
return String.Empty;
}
return String.Empty;
The code above works fine, but there are a few things I can't be sure of. Is there a possibility that the hostname with the second code will be return null? If there are two computer names in the same domain(can be possible?), can I get the correct result from the ping result? Is there any other way than these two codes find correctly under all circumstances? Thank you.
I need to get the IP address of a Wi-Fi module, running a TCP server. The application will open the WiFi connections settings page to allow the user to connect to the Wi-Fi module's created network (requiring the password to be entered)- see attached picture. The server (Wi-FI module) IP address is 172.1.4.155 (for example) but when I try to get the IP address in Xamarin.Forms using GetLocalIPAddress() (attached below), the address it returns is the local IP address of the device (Phone)- 172.1.4.55 (for example). I need to be able to get the IP address programmatically without a user input in an Application.
Is there any way to get the IP address of the (external) non-device specific IP address? I assume the returned IP address of the phone is the DHCP assigned IP address. I need to get the server IP address as it is essential to establish a TCP socket connection between the phone and the WiFi module. I have been trying to look for a solution without any success for a few days now so any help/suggestions or examples will be greatly appreciated.
The code below is the GetLocalIPAddress() function to get the IP address.
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
//return "";
}
//throw new Exception("Local IP Address Not Found!");
return "None";
}
How to Read IP Address in XAMARIN Form, i have Created the DependencyServices in both IOS and Android projects and getting a proper IP address. Below is code to get IP address.
In PCL Project
public interface IIPAddressManager
{
String GetIPAddress();
}
In IOS Project
[assembly: Dependency(typeof(YourAppNamespace.iOSUnified.iOS.DependencyServices.IPAddressManager))]
namespace YourAppNamespace.iOSUnified.iOS.DependencyServices
{
class IPAddressManager : IIPAddressManager
{
public string GetIPAddress()
{
String ipAddress = "";
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
{
if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = addrInfo.Address.ToString();
}
}
}
}
return ipAddress;
}
}
}
In Android Project.
[assembly: Dependency(typeof(YourAppNamespace.Android.Android.DependencyServices.IPAddressManager))]
namespace YourAppNamespace.Android.Android.DependencyServices
{
class IPAddressManager : IIPAddressManager
{
public string GetIPAddress()
{
IPAddress[] adresses = Dns.GetHostAddresses(Dns.GetHostName());
if (adresses !=null && adresses[0] != null)
{
return adresses[0].ToString();
}
else
{
return null;
}
}
}
}
Then call a DependencyServices in UI project.
string ipaddress = DependencyService.Get<IIPAddressManager>().GetIPAddress
I'm trying to get the user's IP address from ASP.NET MVC 5. I've looked up various examples, such as these:
https://stackoverflow.com/a/740431/177416
https://stackoverflow.com/a/20194511/177416
https://stackoverflow.com/a/3003254/177416
They've all produced the same result: the user is considered internal to the network. I've had friends try their phones (which are not on the network). Here's my latest attempt:
private static Logger _logger = LogManager.GetCurrentClassLogger();
public static bool IsIpInternal()
{
var ipAddress = HttpContext.Current.Request.UserHostAddress;
var logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, ipAddress);
_logger.Log(logEvent);
try
{
if (ipAddress != null)
{
var ipParts = ipAddress.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
var isDebug = System.Diagnostics.Debugger.IsAttached;
if (ipParts[0] == 10)
{
return true;
}
}
}
catch (Exception e)
{
logEvent = new LogEventInfo(LogLevel.Error, _logger.Name, e.Message);
_logger.Log(logEvent);
return false;
}
return false;
}
The log is showing 10.xxx.xx.xxx for all requests (based on the log). This is an internal address rather than the IP of the client connecting to the web app. The IsIpInternal() returns true always. What am I doing wrong?
Note that I'm ignoring 192.168.x.x and 172.16.xxx.xxx addresses as being internal.
If your web site is behind a load balancer, it is a common problem for the load balancer's IP address to appear when you are expecting the client's IP address. That is because in reality the load balancer is the only client that the web application knows is talking to it.
There are two ways to deal with this:
You can configure the load balancer to add an additional HTTP header (x-forwarded-for) that specifies the original IP address. You will need to modify your web site to look at this header instead of the UserHostAddress, like this:
//var clientIP = HttpContext.Current.Request.UserHostAddress;
var clientIP = HttpContext.Current.Request.Headers["x-forwarded-for"];
Note: The x-forwarded-for header can actually return a comma-delimited list of IP addresses in some cases. So to be compatible with such an occurence, you might write this instead:
var clientIP = HttpContext.Current.Request.Headers["x-forwarded-for"].Split(',')[0];
You can configure certain LBs to pass through the client IP by copying the IP header packet. For Citrix Netscaler, see this article for more information.
I am using VS2012 and Grapevine 3.0.4 , when i use the Grapevine same machine with localhost
hostname , everything works well.
If I want to reach from other PC with client , Server could not be start listening with hostname ip address or Computername
If i try server pc set hostname to localhost , it starts listening but when reached from other PC with IP or name server returns bad request 400
Is it something wrong with my code or library.
My Server code is
public class embeddedHTTP
{
private RESTServer Server;
public void ServerStart()
{
try
{
Server = new RESTServer();
Server.Port = GlobalVars.HttpHostPort;
Server.Host = GlobalVars.HttpHostAdress; // THIS ONLY WORKS FOR LOCALHOST
Server.MaxThreads = 20;
Server.Start();
while (Server.IsListening)
{
Thread.Sleep(GlobalVars.HttpHostRespTime);
}
}
catch (Exception ex)
{
messenger.logque("embedded HTTP server not started, Error ID : 52", 3, null);
}
}
public void ServerStop()
{
Server.Stop();
}
public sealed class MyResource : RESTResource
{
//d+$^ [a-zA-Z]+
[RESTRoute(Method = Grapevine.HttpMethod.GET, PathInfo = #"/")]
public void HandleFooRequests(HttpListenerContext context)
{
//String RawuR = context.Request.RawUrl;
String URL = Convert.ToString(context.Request.Url);
String ResultXML = brain.HTTPCMD(URL);
this.SendTextResponse(context, ResultXML);
}
}
}
If you can't reach the server from a remote machine, you are likely running a firewall that is blocking inbound traffic to the port you are listening on. Try opening the port on your firewall, and see if that works for you.
How to Open a Port in the Windows 7 Firewall
Also, you can listen on all hosts by using the asterisk (*) as your hostname.
Is there a way in c# to check if the app is running on localhost (as opposed to a production server)?
I am writing a mass mailing program that needs to use a certain mail queue is it's running on localhost.
if (Localhost)
{
Queue = QueueLocal;
}
else
{
Queue = QueueProduction;
}
As a comment has the correct solution I'm going to post it as an answer:
HttpContext.Current.Request.IsLocal
What about something like:
public static bool OnTestingServer()
{
string host = HttpContext.Current.Request.Url.Host.ToLower();
return (host == "localhost");
}
Use a value in the application configuration file that will tell you what environment you are on.
Since you are using asp.net, you can utilize config file transforms to ensure the setting is correct for each of your environments.
See if this works:
public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
Reference: http://www.csharp-examples.net/local-ip/
Localhost ip address is constant, you can use it to determines if it´s localhost or remote user.
But beware, if you are logged in the production server, it will be considered localhost too.
This covers IP v.4 and v.6:
public static bool isLocalhost( )
{
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
return (ip == "127.0.0.1" || ip == "::1");
}
To be totally sure in which server the code is running at, you can use the MAC address:
public string GetMACAddress()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
} return sMacAddress;
}
from: http://www.c-sharpcorner.com/uploadfile/ahsanm.m/how-to-get-the-mac-address-of-system-using-Asp-NetC-Sharp/
And compare with a MAC address in web.config for example.
public static bool isLocalhost( )
{
return GetMACAddress() == System.Configuration.ConfigurationManager.AppSettings["LocalhostMAC"].ToString();
}
Unfortunately there is no HttpContext.HttpRequest.IsLocal() anymore within core.
But after checking the original implementation in .Net, it is quite easy to reimplement the same behaviour by checking HttpContext.Connection:
private bool IsLocal(ConnectionInfo connection)
{
var remoteAddress = connection.RemoteIpAddress.ToString();
// if unknown, assume not local
if (String.IsNullOrEmpty(remoteAddress))
return false;
// check if localhost
if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
return true;
// compare with local address
if (remoteAddress == connection.LocalIpAddress.ToString())
return true;
return false;
}
Or, you could use a C# Preprocessor Directive if your simply targeting a development environment (this is assuming your app doesn't run in debug in production!):
#if debug
Queue = QueueLocal;
#else
Queue = QueueProduction;
just like this:
HttpContext.Current.Request.IsLocal
string hostName = Request.Url.Host.ToString();
I know this is the really old thread but still, someone looking for a straight solution then you can use this:
if (HttpContext.Current.Request.Url.Host == "localhost")
{
//your action when app is running on localhost
}
This is an alternative, more transparent, option:
public static bool IsLocal
{
// MVC < 6
get
{
var authority = HttpContext.Request.Url.Authority.ToLower();
return authority == "localhost" ||
authority.StartsWith("localhost:");
}
// MVC 6+
get
{
return String.Compare(HttpContext.Request.Url.Host, "localhost",
StringComparison.OrdinalIgnoreCase);
}
}
If you're not doing this in the Controller then add Current after HttpContext, as in HttpContext.Current.Request...
Also, in MVC 6, in the View, HttpContext is just Context