I read this question in this thread: How to get the IP address of the server on which my C# application is running on?
But this code is not working for me:
string hostname = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(hostname);
It giving me an err on this second line in the argument:
A field initializer cannot reference
the non-static field, method, or
property.
I want to store my local IP of my machine in a string. Thats all!
public static String GetIP()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
//This will return the collection of local IP's
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
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;
}
//Call this method this will tell Is this your local Ip
IsLocalIpAddress("localhost");
In ASP.Net, you can get the IP address to which the request was made from the Request object:
string myIpAddress = Request.UserHostAddress ;
It may be an IPv4 address or an IPv6 address. To find out, parse it into an System.Net.IPAddress:
IPAddress addr = IPAddress.Parse( myIpAddress ) ;
If you're interested in the IP address of the current host, that turns into a much more complicated (interesting?) question.
Any given host (and for "host" read "individual computer") may have multiple NICs (Network Interface Card) installed. Each NIC (assuming it's attached to an IP network) has an IP address assigned to it—and likely it has both an IPv4 and an IPv6 address assigned to it.
Further, each NIC may itself be multi-homed and have additional IP addresses, either IPv4 and/or IPv6 assigned.
Then we have the IP loopback adapter, for which each host shares the same loopback addresses. For IPv4, the loopback address is defined as the entire 127/8 subnet (that is, IP addresses 127.0.0.0–127.255.255.255 are all IPv4 loopback addresses). IPv6 only assigns a single loopback address (::1).
So, from the vantage point of the host then, you need to know the context (loopback adapter or NIC? if NIC, which one? Ipv4 or IPv6?) And even then, you're not guaranteed a single IP address. You have to ask yourself what, exactly, it is you mean by "my IP address"?
Related
I try type ipconfig on cmd.exe and ip address ="172.24.70.68"
But If i get IP of this PC, it return IP: 127.0.0.1
This my code get IP Address:
IPAddress ip = null;
IPAddress mask = null;
//++**********************************
// Get IP
//--**********************************
strHostName = Dns.GetHostName();
IPHostEntry iphe = Dns.GetHostEntry(strHostName);
foreach (IPAddress ipheal in iphe.AddressList)
{
if (ipheal.AddressFamily ==AddressFamily.InterNetwork)
{
ip = ipheal;
break;
}
}
Why IP Address return value 127.0.0.1?
Some other PCs, it getting IP is ok.
Try not to get the address via DNS, which may be deceiving or simply not working if for example there are no DNS records for the computer, but via the adapter settings, which is essentially the same ipconfig does.
You can get all of the adapters with NetworkInterface.GetAllNetworkInterfaces(). The NetworkInterfaceType property let's you filter for Ethernet adapters as well as exclude the loop back adapter. You can also filter only for adapters in a particular status, e.g. up, with the OperationalStatus property.
You can then loop through all the unicast addresses of the adapter and pick one of the IPv4 addresses from it, for example the first one encountered. Of course, if you have more adapters or addresses on one adapter this might still not be the one you're looking for. In that case you need to define how to recognize the one you want and implement that accordingly.
IPAddress ip = null;
IPAddress mask = null;
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
bool found = false;
if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet
&& networkInterface.OperationalStatus == OperationalStatus.Up
&& networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
foreach (UnicastIPAddressInformation unicastIPAddressInformation in networkInterface.GetIPProperties().UnicastAddresses)
{
if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
{
ip = unicastIPAddressInformation.Address;
mask = unicastIPAddressInformation.IPv4Mask;
found = true;
break;
}
}
}
if (found)
{
break;
}
}
You need to use forwarder Header
.net core example
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardLimit = 2;
options.KnownProxies.Add(IPAddress.Parse("127.0.10.1"));
options.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto;
});
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
In my app I need to display IP addresses of each available (wifi or ethernet) adapter.
Problem is I get more then one IP address per adapter, and last one I get (per adapter) is one I'm looking for.
I dont know what for are first two (usually they are first two) IP addresses and how to get "real" IP address. I compared these two IP addresses that I get before "real" one with CMD and "ipconfig" command and they are not mentioned there, so its not default gateway, subnet mask,local Ipv6 or public IP address.
This is what my app outputs:
This is what I want:
Code I use:
foreach (NetworkInterface inf in devs)
{
if (inf.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || inf.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation address in inf.GetIPProperties().UnicastAddresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
MessageBox.Show(address.Address.ToString());
}
}
}
Here is the answer on how to get IP addresses (IPv4 and IPv6) per adapter.
NetworkInterface[] intf = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface device in intf)
{
IPAddress ipv6Address = device.GetIPProperties().UnicastAddresses[0].Address; //This will give ipv6 address of certain adapter
IPAddress ipv4Address = device.GetIPProperties().UnicastAddresses[1].Address; //This will give ipv4 address of certain adapter
}
I don't know if I'm just not searching using the right keywords, I want to be able to find the IP address of my local computer that was assigned by my router.
I was using:
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach(IPAddress ip in host.AddressList)
{
if(ip.addressfamily.tostring() == "InterNetwork")
{
return ip;
}
}
The problem is I have multiple InterNetwork ip addresses because I use virtual services, so I need to be able to identify which one was assigned by my router.
How about loopback?
if (IPAddress.IsLoopback(ip)) return ip; //localhost
Or try pinging the local machine
Ping pingSender = new Ping ();
IPAddress address = IPAddress.Loopback;
PingReply reply = pingSender.Send (address);
if (reply.Status == IPStatus.Success){..}
also this might help you
Showing The External IP-Address In C#
I have 3 different network cards each with their individual responsibility. Two of the cards are receiving packets from a similar device (plugged directly into each individual network card) which sends data on the same port. I need to save the packets knowing which device they came from.
Given that I am required to not specify the ip address of the devices sending me the packets, how can I listen on a given network card? I am allowed to specify a static ip address for all 3 nics if needed.
Example: nic1 = 169.254.0.27, nic2 = 169.254.0.28, nic3 = 169.254.0.29
Right now I have this receiving the data from nic1 and nic2 without knowing which device it came from.
var myClient = new UdpClient(2000) //Port is random example
var endPoint = new IPEndPoint(IPAddress.Any, 0):
while (!finished)
{
byte[] receivedBytes = myClient.Receive(ref endPoint);
doStuff(receivedBytes);
}
I can't seem to specify the static ip address of the network cards in a manner which will allow me to capture the packets from just one of the devices. How can I separate these packets with only the knowledge that they are coming in on two different network cards?
Thank you.
You're not telling the UdpClient what IP endpoint to listen on. Even if you were to replace IPAddress.Any with the endpoint of your network card, you'd still have the same problem.
If you want to tell the UdpClient to receive packets on a specific network card, you have to specify the IP address of that card in the constructor. Like so:
var listenEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 2000);
var myClient = new UdpClient(listenEndpoint);
Now, you may ask "What's the ref endPoint part for when I'm calling myClient.Receive(ref endPoint)?" That endpoint is the IP endpoint of the client. I would suggest replacing your code with something like this:
IPEndpoint clientEndpoint = null;
while (!finished)
{
var receivedBytes = myClient.Receive(ref clientEndpoint);
// clientEndpoint is no longer null - it is now populated
// with the IP address of the client that just sent you data
}
So now you have two endpoints:
listenEndpoint, passed in through the constructor, specifying the address of the network card you want to listen on.
clientEndpoint, passed in as a ref parameter to Receive(), which will be populated with the client's IP address so you know who is talking to you.
Check this out this:
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine("Name: " + netInterface.Name);
Console.WriteLine("Description: " + netInterface.Description);
Console.WriteLine("Addresses: ");
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
{
Console.WriteLine(" " + addr.Address.ToString());
}
Console.WriteLine("");
}
Then you can choose on which address start listening.
look, if you create your IPEndPoint in the following way it must work:
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
...
try to do not pass 0 as port but a valid port number, if you run this code and break the foreach after the first iteration you will have created only 1 IPEndPoint and you can use that one in your call to: myClient.Receive
notice that the UdpClient class has a member calledd Client which is a socket, try to explore the properties of that object as well to find out some details, I have found the code I gave you here: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx