How to get IPv4 IP rather then loopback ip - c#

I'm developing an application which needs user systems IP address for that i used below code
Get IP
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress i in localIPs)
{
if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
txtIP.Text = i.ToString();
}
}
In many systems it works very fine but some time it captures Loop-Back ip address 127.0.0.1. Can any one guide me how can i prevent application to capture loop-back IP.

Just filter the loopback IP
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress i in localIPs)
{
if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
&& !IPAddress.isLoopback(i))
{
txtIP.Text = i.ToString();
}
}

Related

Get ALL IP addresses that contains X hostname in LAN (Multiple same hostnames)

I'm trying to loop through all IP address within range (192.168.1.1 - 192.168.1.255) and print out the IP address that contains X hostname.
I am trying to use this code, but it only give me the last IP address which contains X hostname, but there are multiple IP addresses with this hostname:
string customPc = "myCustomPc";
IPHostEntry host = Dns.GetHostEntry(customPc);
foreach (IPAddress theaddress in host.AddressList)
{
Console.WriteLine(theaddress.ToString());
}
also, I am trying to do it this way, but it prints out the same result - the last IP address that has this hostname:
string host = "myCustomPc";
IPHostEntry hostEntry;
hostEntry = Dns.GetHostEntry(host);
if (hostEntry.AddressList.Length > 0)
{
var ip = hostEntry.AddressList[0];
Console.WriteLine(ip + ": Your custom PC is found!");
}`
Is you problem that you're printing only one element from the AddressList collection?
Try this:
foreach(var a in hostEntry.AddressList) {
Console.WriteLine(a + ": Your custom PC is found!");
}
or use Dns.GetHostAddresses(String) Method
foreach(var a in Dns.GetHostAddresses(host)) {
Console.WriteLine(a);
}
how can I loop from 192.168.1.1 to 192.168.1.255
Here's one way
for(int d = 1; d <=255; d++)
{
var ipstr = $"192.161.1.{d}";
}

Convert hostname to only one IP Address

I want to create hostname to IP address and vice versa converter. However I got a problem in which 1 hostname return 2 IP addresses and when I reconvert the IP address to hostname, only one of them return the correct hostname.
Example for convert CEGN5CG7260FR7.xxxxx.xxx it return 192.168.X.XX and 10.132.XXX.XXX but when reconvert back to hostname, only 10.132.XXX.XXX return the correct hostname.
This code snip for convert hostname to IP address:-
// Convert hostname to IP address
IPHostEntry host = Dns.GetHostEntry(hostList[i]);
IPAddress[] ipaddr = host.AddressList;
// Loop through the IP Address array and add the IP address to IP List
foreach (IPAddress addr in ipaddr)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipList.Add(addr.ToString());
}
}
// Display items in IP Address textbox
foreach (var ip in ipList)
{
ips += ip + Environment.NewLine;
}
txtIP.Text = ips;
This code snip for convert IP address to hostname:-
// Convert IP address to hostname
IPHostEntry IP = Dns.GetHostEntry(IPAddress.Parse(ip));
if (IP != null)
{
hostList.Add(IP.HostName);
}
// Display items in Hostname textbox
foreach (var hn in hostList)
{
hosts += hn + Environment.NewLine;
}
txtHost.Text = hosts;
What I can do to only get and display 10.132.XXX.XXX IP address and ignore the first one?
You can try this code to find correct 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();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}

get Local IP from connected networkcard

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());
}
}
}
}

Getting local host Ip Address [duplicate]

This question already has answers here:
Get local IP address
(26 answers)
Closed 7 years ago.
public static string GetLocalIpAddress()
{
string hostName = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(hostName);
string IpAddress = Convert.ToString(ip.AddressList[2]);
return IpAddress.ToString();
}
This will some times show Index out of bound exception
what should be the problem in it.?
thanks in advance
try this method, it works for me.
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;
}
Thanks,
foreach (var addr in Dns.GetHostEntry(string.Empty).AddressList)
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
Console.WriteLine("IPv4 Address: {0}", addr)
}
As they have answering before. You should check your lenght on the AddressList. Becouse it will not always be 2.
Here you have another answer on stackoverflow:
Getting valid IP from IPHostEntry

How to get the IP address of a machine in C#

How do I get the IP address of a machine in C#?
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
Your machine doesn't have a single IP address, and some of the returned addresses can be IPv6.
MSDN links:
Dns.GetHostAddresses
IPAddress
Alternatively, as MSalters mentioned, 127.0.0.1 / ::1 is the loopback address and will always refer to the local machine. For obvious reasons, however, it cannot be used to connect to the local machine from a remote machine.
My desired answer was
string ipAddress = "";
if (Dns.GetHostAddresses(Dns.GetHostName()).Length > 0)
{
ipAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
}
IPHostEntry ip = DNS.GetHostByName (strHostName);
IPAddress [] IPaddr = ip.AddressList;
for (int i = 0; i < IPaddr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, IPaddr[i].ToString ());
}
string hostName = Dns.GetHostName(); // Retrive the Name of HOST
// Get the IP
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
//use Following Namespace-
using System.Net;
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); //get all network interfaces
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); // get all IP addresses based on the local host name
foreach (NetworkInterface adapter in adapters) //for each Network interface in addapters
{
IPInterfaceProperties properties = adapter.GetIPProperties(); // get the ip properties from the adapter and store them into properties
foreach (UnicastIPAddressInformation ip in properties.UnicastAddresses) // for each UnicastIPAddressInformation in the IPInterfaceProperties Unicast address( this assocaites the IP address with the correct adapter)
{
//if the operationalStatus of the adapter is up and the ip Address family is in the Internwork
if ((adapter.Name == "Ethernet" || adapter.Name == "Ethernet 2") && (ip.Address.AddressFamily == AddressFamily.InterNetwork)) //test against the name of the adapter you want to get
{
ipAddress = ip.Address.ToString();
}//end if
}//end inner for, the UnicastIPAddressInformation for
}

Categories

Resources