I try to get my local ip, the code below shows you how i do that.
The problem with this is when i'm connectet to wifi and my ethernet-card is not connected
it gives me a 169.xxx.xxx.xxx adress.
How can i make a check to see wich networkcard is connected, and get that ip
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "127.0.0.1";
}
I use this:
List<IPAddress> addresses = new List<IPAddress>();
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkItf in networkInterfaces)
{
// check whether turned on
if (networkItf.OperationalStatus == OperationalStatus.Up)
{
// read the IP configuration for each network
IPInterfaceProperties properties = networkItf.GetIPProperties();
// each network interface may have multiple IP addresses
foreach (IPAddressInformation address in properties.UnicastAddresses)
{
// filter only IPv4 addresses, if required...
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
// ignore loopback addresses (e.g., 127.0.0.1)
if (IPAddress.IsLoopback(address.Address))
continue;
// add result
addresses.Add(address.Address);
}
}
}
You can use the NetworkInterface class to see if there is a network interface that is indeed connected. Take a look at the relevant documentation here: https://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface(v=vs.110).aspx
This code snippet should give you the result you are interested in:
private string GetLocalIP()
{
var isConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (isConnected)
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
}
return "127.0.0.1";
}
this works for me https://stackoverflow.com/a/27376368/7232036
private string localIP()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address.ToString();
}
}
this will give the IP addresses you are looking for
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(ip.Address.ToString());
}
}
}
}
Related
I need to get the Local IP address of PC but if pc is connected to multiple network the ip is not correct.
I'm using:
public static string GetIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
Like:
I need get the local ip of adapter with internet or all local ip address.
I can see 2 options:
option 1
loop trough all interfaces using System.Net.NetworkInformation:
static List<IPAddress> GetIpAddress()
{
List<IPAddress> AllIps = new List<IPAddress>();
foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties properties = netif.GetIPProperties();
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
{
AllIps.Add(unicast.Address);
Console.WriteLine(unicast.Address);
}
}
return AllIps;
}
option 2
find the default gateway to the internet, then match the default gateway address to the interface addresses you found:
public static IPAddress GetDefaultGateway()
{
IPAddress result = null;
var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();
if (cards.Any())
{
foreach (var card in cards)
{
var props = card.GetIPProperties();
if (props == null)
continue;
var gateways = props.GatewayAddresses;
if (!gateways.Any())
continue;
var gateway =
gateways.FirstOrDefault(g => g.Address.AddressFamily.ToString() == "InterNetwork");
if (gateway == null)
continue;
result = gateway.Address;
break;
};
}
return result;
}
now you can combine the 2 options in order to find the interface that is connected to the internet. here is my suggestion to match the default gateway to the correct adapter address. you can also determine the IP address classes
using the IpClass Enumeration that is written in the code i have added:
static void Main(string[] args)
{
// find all interfaces ip adressess
var allAdaptersIp = GetIpAddress();
// find the default gateway
var dg = GetDefaultGateway();
// match the default gateway to the host address => the interface that is connected to the internet => that print host address
Console.WriteLine("ip address that will route you to the world: " + GetInterNetworkHostIp(ref allAdaptersIp, dg, IpClass.ClassC));
Console.ReadLine();
}
enum IpClass
{
ClassA,
ClassB,
ClassC
}
static string GetInterNetworkHostIp(ref List<IPAddress> adapters, IPAddress dg, IpClass ipclassenum)
{
string networkAddress = "";
var result = "" ;
switch (ipclassenum)
{
case IpClass.ClassA:
networkAddress = dg.ToString().Substring(0, dg.ToString().Length - dg.ToString().LastIndexOf(".") );
break;
case IpClass.ClassB:
networkAddress = dg.ToString().Substring(0, dg.ToString().Length - dg.ToString().IndexOf(".",3));
break;
case IpClass.ClassC:
networkAddress = dg.ToString().Substring(0, dg.ToString().Length- dg.ToString().IndexOf(".") );
break;
default:
break;
}
foreach (IPAddress ip in adapters)
{
if (ip.ToString().Contains(networkAddress))
{
result = ip.ToString();
break;
}
}
if (result == "")
result = "no ip was found";
return result;
}
I'm trying to get local ip address using this code in my website:
string ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
The scenario is I try to call the website from 2 different ip address, the first call has been successfully but the second one is still displaying the first ip address.
But if I open the web using CTRL+SHIFT+R then both ip address were correct.
Somehow, the string ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; is not refreshing and carried out the cache from previous call.
How do I get around this?
Below are several codes to get local ip address but it didn't work, it can only get the server ip (IIS IP) not the local ip
//code no 1
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
//code no : 2
public static string[] GetAllLocalIPv4(NetworkInterfaceType _type)
{
List<string> ipAddrList = new List<string>();
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddrList.Add(ip.Address.ToString());
}
}
}
}
return ipAddrList.ToArray();
}
//code no 3
public string GetLocalIpAddress2()
{
UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != OperationalStatus.Up)
continue;
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
continue;
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
if (IPAddress.IsLoopback(address.Address))
continue;
if (!address.IsDnsEligible)
{
if (mostSuitableIp == null)
mostSuitableIp = address;
continue;
}
// The best IP is the IP got from DHCP server
if (address.PrefixOrigin != PrefixOrigin.Dhcp)
{
if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
mostSuitableIp = address;
continue;
}
return address.Address.ToString();
}
}
return mostSuitableIp != null
? mostSuitableIp.Address.ToString()
: "";
}
//code no 4
public string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Thanks,
Sam
Hi I'm trying to get my local ip4 address but the result only returning the IP of the IIS Server
here's my code:
public string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
return output;
}
string IPAddress = GetLocalIPv4(NetworkInterfaceType.Ethernet);
The IIS Authentication is I only enable the windows authentication, because I'm using window authentication. But why the returning ip is not my local ip4 instead the IIS server address?
In general:
HttpContext.Current.Request.UserHostAddress;
Tedious approach:
using System.Net.Sockets;
foreach(IPAddress ip in Dns.GetHostEntry(System.Environment.MachineName.AddressList){
if(ip.AddressFamily == AddressFamily.InterNetwork)
Console.WriteLine("IPV4"+ip.ToString());
if(ip.AddressFamily == AddressFamily.InterNetworkV6)
Console.WriteLine("IPV6"+ip.ToString());
Source: https://msdn.microsoft.com/en-us/library/system.net.sockets.addressfamily(v=vs.110).aspx
I need to find out the local Ip address, for that reason I was using the following code:
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
return localIP;
I find out that when a PC has more than one IP with AddressFamily.InterNetwork I get always the first one. However I can't find any property to find out the active IP.
How can I get the correct IP?
Thanks for any tip!
I have picked this up from internet a while ago.
string strHostName = System.Net.Dns.GetHostName(); ;
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
This should give you an array of all the ip addresses of your pc.
Bwall has a fitting solution posted in this thread.
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(ip.Address.ToString());
}
}
}
}
The important thing in this piece of code is, that it only lists IP addresses of ethernet and wireless interfaces. I doubt you'll have a serial connection active, so this won't matter most likely. Alternativly you can always edit the if statement.
//EDIT
If you only want to IP address which actually connects to the internet use Hosam Aly's solution
This is his code:
static IPAddress getInternetIPAddress()
{
try
{
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress gateway = IPAddress.Parse(getInternetGateway());
return findMatch(addresses, gateway);
}
catch (FormatException e) { return null; }
}
static string getInternetGateway()
{
using (Process tracert = new Process())
{
ProcessStartInfo startInfo = tracert.StartInfo;
startInfo.FileName = "tracert.exe";
startInfo.Arguments = "-h 1 www.example.com
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
tracert.Start();
using (StreamReader reader = tracert.StandardOutput)
{
string line = "";
for (int i = 0; i < 5; ++i)
line = reader.ReadLine();
line = line.Trim();
return line.Substring(line.LastIndexOf(' ') + 1);
}
}
}
static IPAddress findMatch(IPAddress[] addresses, IPAddress gateway)
{
byte[] gatewayBytes = gateway.GetAddressBytes();
foreach (IPAddress ip in addresses)
{
byte[] ipBytes = ip.GetAddressBytes();
if (ipBytes[0] == gatewayBytes[0]
&& ipBytes[1] == gatewayBytes[1]
&& ipBytes[2] == gatewayBytes[2])
{
return ip;
}
}
return null;
}
What it basically does, is trace the route to www.example.com and processes the right IP from there. I tested the code on my machine and needed to change the iterations from 9 to 5 to get the right line from stream. You better recheck it or you might into a NullReferenceException because line will be null.
static string GetActiveIP()
{
string ip = "";
foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
{
if (f.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipInterface = f.GetIPProperties();
if (ipInterface.GatewayAddresses.Count > 0)
{`enter code here`
foreach (UnicastIPAddressInformation unicastAddress in ipInterface.UnicastAddresses)
{
if ((unicastAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) && (unicastAddress.IPv4Mask.ToString() != "0.0.0.0"))
{
ip = unicastAddress.Address.ToString();
break;
}
}`enter code here`
}
}
}
return ip;
}
Let's say that I want to send an udp message to every host in my subnet (and then receive an udp message from any host in my subnet):
at the moment I do:
IPAddress broadcast = IPAddress.Parse("192.168.1.255");
but of course I want this to be done dinamically in the event that the subnet is different from 192.168.1/24. I've tried with:
IPAddress broadcast = IPAddress.Broadcast;
but IPAddress.Broadcast represents "255.255.255.255" which can't be used to send messages (it throws an exception)...so:
how do I get the local network adapter broadcast address (or netmask of course)?
THIS IS THE FINAL SOLUTION I CAME UP WITH
public IPAddress getBroadcastIP()
{
IPAddress maskIP = getHostMask();
IPAddress hostIP = getHostIP();
if (maskIP==null || hostIP == null)
return null;
byte[] complementedMaskBytes = new byte[4];
byte[] broadcastIPBytes = new byte[4];
for (int i = 0; i < 4; i++)
{
complementedMaskBytes[i] = (byte) ~ (maskIP.GetAddressBytes().ElementAt(i));
broadcastIPBytes[i] = (byte) ((hostIP.GetAddressBytes().ElementAt(i))|complementedMaskBytes[i]);
}
return new IPAddress(broadcastIPBytes);
}
private IPAddress getHostMask()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in Interfaces)
{
IPAddress hostIP = getHostIP();
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
if (UnicatIPInfo.Address.ToString() == hostIP.ToString())
{
return UnicatIPInfo.IPv4Mask;
}
}
}
return null;
}
private IPAddress getHostIP()
{
foreach (IPAddress ip in (Dns.GetHostEntry(Dns.GetHostName())).AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip;
}
return null;
}
If you get the local IP and subnet, it should be no problem to calculate.
Something like this maybe?
using System;
using System.Net.NetworkInformation;
public class test
{
public static void Main()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface Interface in Interfaces)
{
if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
if (Interface.OperationalStatus != OperationalStatus.Up) continue;
Console.WriteLine(Interface.Description);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);
Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
}
}
}
}
How to calculate the IP range when the IP address and the netmask is given? Should give you the rest of it.