I got a problem synchronizing the "IP address and Description".
The objective is this:
Get the IP address and what is the description?
Example:
| Atheros Azx1234 Wireless Adapter |
|192.168.1.55 |
But the outcome is not what I expected...
This is my code feel free to try...
private void button1_Click(object sender, EventArgs e)
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (NetworkInterface adapter in interfaces)
{
foreach (IPAddress ip in host.AddressList)
{
if ((adapter.OperationalStatus.ToString() == "Up") && // I have a problem with this condition
(ip.AddressFamily == AddressFamily.InterNetwork))
{
MessageBox.Show(ip.ToString(), adapter.Description.ToString());
}
}
}
}
How can I fix this problem?
The problem in your code is that you do not use the associated IP addresses
for the given adapter. Instead of matching all IP addresses to every adapter
use only the IP addresses associated with the current adapter:
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces)
{
var ipProps = adapter.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((adapter.OperationalStatus == OperationalStatus.Up)
&& (ip.Address.AddressFamily == AddressFamily.InterNetwork))
{
Console.Out.WriteLine(ip.Address.ToString() + "|" + adapter.Description.ToString());
}
}
}
Related
I have tried below code but it keeps on giving the me iPhone(ie.Device) IP Address. But I want to get a ROUTER IP ADDRESS
public string GetIPAddress()
{
String ipAddress = "";
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine(netInterface);
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();
}
}
}
}
iPhone IPAddress: 192.168.0.19
Router: 192.168.0.1
I can do the Hacky way of removing the '9' from the last set of IP address. But I don't want to do this.
You can use the following code to get a ROUTER IP ADDRESS(Gateway address) from Android side.
Create a DependenceService in Forms folder.
public interface INetServices
{
string ConvertGateway();
}
Then achieve this interface in the android folder.
[assembly: Dependency(typeof(NetService))]
namespace Forms.Droid
{
class NetService: INetServices
{
[Obsolete]
public string ConvertGateway()
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Service.WifiService);
int ip = wifiManager.ConnectionInfo.IpAddress;
int gateway = wifiManager.DhcpInfo.Gateway;
IPAddress ipAddr = new IPAddress(ip);
IPAddress gatewayAddr = new IPAddress(gateway);
return gatewayAddr.ToString();
}
}
}
And add following permission in the AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
In the Xamarin forms, you can get ROUTER IP ADDRESS like following code.
var gatewayAddress = DependencyService.Get<INetServices>().ConvertGateway();
Console.WriteLine(gatewayAddress);
I can't find code to find the proper IP address to use to open a TCP/IP server port on my machine.
The problem occurs because I have many network adapters. I have some Virtual Machine(s) (for example: HyperV / VirtualBox / VmWare) which create virtual network adapter and each one has its one IPAddress. So how to avoid those IPAddress (proper network card) and find the only one used to access the internet for real?
When I try to find the proper IP Address, I get the virtual network adapter card Ip Adress instead of the physical one using this code:
IPAddress properIpAddress = null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in interfaces)
{
var ipProps = networkInterface.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((networkInterface.OperationalStatus == OperationalStatus.Up) && (ip.Address.AddressFamily == AddressFamily.InterNetwork))
{
if (ip.Address.ToString() == "127.0.0.1")
{
continue;
}
properIpAddress = ip.Address;
// Console.Out.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
Debug.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
break;
}
}
if (properIpAddress != null)
{
break;
}
}
The real solution is to not search for an adapter in the first place.
Just use IPAddress.Any to listen on all interfaces at the given port.
using(TcpListener tcpListener = new TcpListener(IPAddress.Any, somePortNumber))
{
// some code
}
I've been using the following code for this. It gets you the IP that an outgoing connection would use:
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address;
}
Note however, that it does open a socket - so maybe one should cache the result.
I'm now using this code which works fine for me but I'm not sure it is bullet proof.
I share my code as reference because I haven't found something that worked for me, other that this:
IPAddress properIpAddress = null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in interfaces)
{
var ipProps = networkInterface.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((networkInterface.OperationalStatus == OperationalStatus.Up)
&& (ip.Address.AddressFamily == AddressFamily.InterNetwork)
&& (ipProps.IsDnsEnabled || ipProps.IsDynamicDnsEnabled))
{
if (ip.Address.ToString() == "127.0.0.1")
{
continue;
}
properIpAddress = ip.Address;
// Console.Out.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
Debug.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
break;
}
}
if (properIpAddress != null)
{
break;
}
}
I have a VirtualBox VM installed on my machine and as such there is an ethernet adapter that appears for it. I'm enumerating through the list of my machine's IP address via the following:
public string GetLocalIpAddress()
{
try
{
string strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
foreach (IPAddress ip in ipEntry.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return string.Format("({0})", ip.ToString());
}
}
}
catch(Exception e)
{
Global.ApplicationLog.AddApplicationLog(EnumAppEventTypes.SYSTEM_ERROR, e.ToString());
}
return "";
}
My problem is that the virtual machine's ethernet adapter also catches on the condition:
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
Is there a way of picking out my machine's local ip address and disregarding my virtual machine's?
I'm refining Andrej Arh's answer, as the IP Address reported by GatewayAddresses can also be "0.0.0.0" instead of just null:
public static string GetPhysicalIPAdress()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null && !addr.Address.ToString().Equals("0.0.0.0"))
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
return ip.Address.ToString();
}
}
}
}
}
return String.Empty;
}
Use WMI and check ConnectorPresent property for physical device.
public static string GetPhysicalIPAdress()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ConnectorPresent(ni))
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.Address.ToString();
}
}
}
}
}
return string.Empty;
}
private static bool ConnectorPresent(NetworkInterface ni)
{
ManagementScope scope = new ManagementScope(#"\\localhost\root\StandardCimv2");
ObjectQuery query = new ObjectQuery(String.Format(
#"SELECT * FROM MSFT_NetAdapter WHERE ConnectorPresent = True AND DeviceID = '{0}'", ni.Id));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection result = searcher.Get();
return result.Count > 0;
}
There is one option. VM IP don't have Default Gateway, so, exclude all IP's without Default Gateway.
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null)
{
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());
}
}
}
}
}
You can disregard the Ethernet adapter by its name. As the VM Ethernet adapter is represented by a valid NIC driver, it is fully equivalent to the physical NIC of your machine from the OS's point of view.
I am creating a C# winform application, in which I want to change the Public IP Address, NOT the IPv4 Address like (Hotspot-Shield, ZenMate, OpenVPN, and others do).
I have checked the following links but didn't find enough help, so I am posting this question:
How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#
Changing IP address in C#
I write the same code as in the answer of 1st link and also used the libraries but when I check my IP address through google.com it remains the same. I don't know the socket programming.
Here is my code:
namespace WindowsFormsApplication1
{
class ChangeIP
{
public void SetIP(string ipAddress, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
{
using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
{
// Set new IP address and subnet if needed
if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
{
if (!String.IsNullOrEmpty(ipAddress))
{
newIP["IPAddress"] = new[] { ipAddress };
}
if (!String.IsNullOrEmpty(subnetMask))
{
newIP["SubnetMask"] = new[] { subnetMask };
}
managementObject.InvokeMethod("EnableStatic", newIP, null);
}
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
{
newGateway["DefaultIPGateway"] = new[] { gateway };
newGateway["GatewayCostMetric"] = new[] { 1 };
managementObject.InvokeMethod("SetGateways", newGateway, null);
}
}
}
}
}
}
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nic">NIC address</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetNameservers(string nic, string dnsServers)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
{
using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
{
newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
}
}
}
And Here is how I am calling those methods:
{
static string local_ip;
string public_ip;
public static string GetLocalIPAddress() //Method For Getting Local Machine IP
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
// Mehod End
local_ip = GetLocalIPAddress();
ChangeIP ip = new ChangeIP();
ip.SetIP(local_ip, null, null); // Calling Method
var getNIC = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface[] NI = NetworkInterface.GetAllNetworkInterfaces();
string nic = string.Empty;
string dnsServer = string.Empty;
foreach(var r in getNIC)
{
nic = r.Name;
}
foreach(NetworkInterface ninter in NI)
{
if(ninter.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipProperties = ninter.GetIPProperties();
IPAddressCollection dnsAddresses = ipProperties.DnsAddresses;
foreach(IPAddress dnsAdrs in dnsAddresses)
{
dnsServer = dnsAdrs.ToString();
}
}
}
ip.SetNameservers(nic, dnsServer); // Calling Method
public_ip = new WebClient().DownloadString("http://icanhazip.com");
}
How you've described your question is not how the internet (is supposed to) work(s).
Windows doesn't let you write raw IP packets, for this you need to use a TAP/TUN driver. But although you send out packets spoofing the source IP address, the internet between you and the destination won't return the route.
If you're operating behind a block of IP addresses, and only want to spoof another in that block, the return address will get back to your local router, but still won't necessary route back to you.
Unless you use TAP/TUN, there's no other way to steal someone else's Public IP address, excluding other network security vulnerability exploitations which are beyond the scope of this forum.
And even with TAP/TUN you're very limited in what you can achieve over spoofed IP packets in one direction. In fact, ISPs may filter out spoofed IP addresses.
I've got some code here that works great on IPv4 machines, but on our build server (an IPv6) it fails. In a nutshell:
IPHostEntry ipHostEntry = Dns.GetHostEntry(string.Empty);
The documentation for GetHostEntry says that passing in string.Empty will get you the IPv4 address of the localhost. This is what I want. The problem is that it's returning the string "::1:" on our IPv6 machine, which I believe is the IPv6 address.
Pinging the machine from any other IPv4 machine gives a good IPv4 address... and doing a "ping -4 machinename" from itself gives the correct IPv4 address.... but pinging it regularly from itself gives "::1:".
How can I get the IPv4 for this machine, from itself?
Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find or Array.FindLast if you just want one.
IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable
and use in any function of the form.
public static string GetIPAddress(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
//System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
return ip.ToString();
}
}
return string.Empty;
}
To find all valid address list this is the code I have used
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
You can get all IPv4 address from the DNS using this code:
IPs[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
address => address.AddressFamily == AddressFamily.InterNetwork);
IPv6
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()
IPv4
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()