I have three Ethernet Adapters on my windows machine. All show status connected and up.
I want to understand how can I find from PowerShell which adapter is being used to connect to the internet. Via UI I can see Ethernet0 being the one but how to find that via powershell. Any ideas are welcomed. Especially something that is supported in powershell 2 as well.
PS C:\Users> Get-NetAdapter -physical
Name InterfaceDescription ifIndex Status
Ethernet0 Intel(R) 82574L Gigabit Network Conn... 15 Up
Ethernet1 Intel(R) 82574L Gigabit Network Co...#2 9 Up
Ethernet2 Intel(R) 82574L Gigabit Network Co...#3 4 Up
Get-NetAdapterStatistics will return information such as traffic on the adapter specified which you can use to create a script to listen for a change in value.
Here's some quick and dirty scripting using that cmdlet:
$keySet = #{}
:loop while ($true) {
$adapters = Get-NetAdapter -Physical | Get-NetAdapterStatistics
foreach ($adapter in $adapters)
{
if (-not $keySet.ContainsKey($adapter.Name)) {
$null = $keySet.Add($adapter.Name,$adapter.ReceivedBytes)
}
if ($adapter.ReceivedBytes -ne $keySet[$adapter.Name]) {
Write-Output -InputObject $adapter.Name
Break loop
}
}
}
By creating a hashtable, you can append the Name and ReceivedBytes property to it. Then reference the key values later on in your second iteration to compare from your first iteration. Using a while loop, you can set a constant listener to see which adapter will be the first to receive a packet; this in turn gives a different value of what's stored in $keySet and will break you out of the loop but not before outputting the Name of the adapter.
The issue comes with the adapters that are receiving any other traffic. That's something to be weary of. That is also something you can improve on later on down the road if you want to continue to use this example.
Hopefully this gets you on the right track.
Related
I have a windows 10 system on which there are 2 NIC's, both connected to different networks and both of them are assigned static IPs (Eg: IP_1=170.30.120.1 and IP_2=10.20.20.1).
When the Network_2 is down momentarily only IP_1 is listed in the commandline when Ipconfig commands were used. Is there a way for me to retrieve both the static IPs even if the network is momentarily down?
I have tried ipconfig , powershell commands and few more. Since the static IPs are assigned to both, can I get both IPs irrespective of their network state?
You can try PowerShell script to get the NetworkAdapterConfiguration object and Filter based on DHCPEnabled to be false.
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter DHCPEnabled=False -ComputerName . |Format-Table
This formats the output in a table format. However, you can play around with the command a bit more to get the desired output format and information by changing Filter etc.
I'm looking to make a basic Powerscript to enable wifi and disable ethernet if the ethernet adapter is up and vice versa. Was thinking something like
If (Get-NetAdapter ethernet == Status Up)
Enable-NetAdapter wi-fi
Disable-NetAdapter ethernet
Else
Enable-NetAdapter ethernet
Disable-NetAdapter wi-fi
but I am having issues with writing the if statement to actually get the status of the network adapter. How do I properly write the If statement?
there are a lot of about topics that come with powershell.
for the IF statement you can check :
Get-Help about_if
for what you are trying to do:
if( (Get-NetAdapter -Name ethernet).Status -eq 'UP')
{
#some code
}
else
{
#some code
}
Let's say I have Windows 7 with one real network interface and few loopback interfaces.
I have IOCP enabled server that accepts connections from clients.
I'm trying to simulate as much as possible real client connections to the server.
My client code simply establishes X amount of socket connections
(note that client binds to a given interface):
const Int32 remotePort = 12345;
const Int32 MaxSockets = 60000;
Socket[] s = new Socket[MaxSockets];
IPEndPoint bindEndpoint = new IPEndPoint(IPAddress.Parse(args[0]), 0);
for (Int32 i = 0; i < MaxSockets; i++)
{
s[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s[i].SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
s[i].Bind(bindEndpoint);
s[i].Connect(args[1], remotePort);
IPEndPoint socketInfo = (IPEndPoint)s[i].LocalEndPoint;
Console.WriteLine(String.Format("Connected socket {0} {1} : {2}", i, socketInfo.Address, socketInfo.Port));
}
On a loopback interface I have several IPs that I use for binding.
In addition, I also use real interface to bind on.
I ran into a problem when amount of opened sockets is around 64K per machine:
Unhandled Exception: System.Net.Sockets.SocketException: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full
I've tried several helpless things like:
- setting MaxUserPort to max value and some other recommended TCPIP settings in the registry.
- trying to run two servers on different interfaces (real interfaces and loopback) and using several clients.
Is it a known limitation in Windows or its possible to overcome it somehow?
Thanks for the help!
I have found on some Microsoft page that:
... HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort
registry subkey is defined as the maximum port up to which ports may be allocated for wildcard binds. The value of the MaxUserPort registry entry defines the dynamic port range...
So, if I force the endpoint to use a certain port, e.g.
IPEndPoint bindEndpoint = new IPEndPoint(IPAddress.Parse(args[0]), 54321);
Then I can open more than 64K simultaneous sockets in the system.
In your code example, you are calling Bind(bindEndpoint), but you do not show how bindEndpoint is defined. Check that :
Your system actually has multiple IP addresses (loopback does not count)
You are actually setting the IP Address of the endpoint to an IP address (not loopback)
The binds are being spread across multiple IP addresses
The loopback address does not count because many systems treat it specially for routing and binding purposes. So binding to ports in loopback may be sucking up the ports across all addresses the same as if you were binding to INADDR_ANY (0.0.0.0).
Both TCP and UDP use an unsigned 16-bit integer to designate port number. I don't imagine any implementation in any operating system is going to be able to open more than 65535 sockets per bound address at best. Additionally, I wouldn't be surprised if Windows doesn't implement fully isolated state tables for each adapter or each bound address but instead relies on a global state table. If that is the case, it would be a Windows network architecture limit instead of a soft, configurable limit.
I've developed a load testing tool.
Running on Windows 10/16G RAM, it could created 60,000 connections with server successfully.
But when try to create more connections, the tool will report "socket WinError 10055 No Buffer Space Available" soon.
Accord to this article, I think the limitation is the overall socket buffer size of whole OS, not the number of opened file.
I am using WMI to detect a number of items about a network adapter's state. Among the things I need to find out are (a) speed and (b) duplex.
I have been able to detect the speed of a network adapter by using WMI and the following Python code:
from pycom.client import wmi
dev_name = r"\\DEVICE\\{287EB4BB-5C2A-4108-B377-15E1D0B0E760}"
query1 = """
SELECT *
FROM MSNdis_EnumerateAdapter
WHERE DeviceName = '%s'""" % dev_name
wmi_ndis = wmi.WMI("root\\WMI")
results = wmi_ndis.ExecQuery(query1)
instance_name = results[0].InstanceName
del results
query2="""
SELECT *
FROM MSNdis_LinkSpeed
WHERE InstanceName='%s'""" % instance_name
results = wmi_ndis.ExecQuery(query2)
linkspeed = results[0].NdisLinkSpeed
del results
print instance_name, linkspeed
del instance_name
del linkspeed
del wmi_ndis
There appears to be a perfect class for the data I want: MSNDis_LinkParameters. However, this table does not appear to be populated. There are values in Win32_NetworkAdapter as well, but they are also not populated.
I would be happy to use a native C API or WMI, but I can't do screen scraping because the application needs to work with arbitrary languages. Thanks!
Apparently the underlying issue here is that WMI provider implementation is handled by the NIC vendor, not the OS-- so some NICs may support some settings while (as you've discovered) others don't.
For link speed, check out this for some WMI scripts which may work on most NICs.
For duplex, I think you're out of luck, at least according to topic. Look at the last post in that thread-- it seems pretty specific about how to work around the limit in some cases, but won't work for all NICs.
i want to write a script to manipulate the dhcp.conf file. which in the sense, it has to read the file and it should ping all the lease IP and should give another text file, in which it should give the list of IPs, which devices are now existing.
EDIT: thanks for your swift reply. dhcpd.conf file is like this
lease 172.31.0.10 {
some text
some text1
}
lease 172.31.0.12 {
some text
some text1
}
lease 172.31.0.100 {
some text
some text1
}
so first i need to extract the ip address first and one by one we have to ping
Assumptions
First, there are two things you need to be aware of:
Not all devices respond to ping. Quite a few PC firewalls disable
ping replies. If you're on Ethernet, arping can be used instead and
will even detect firewalled PCs.
dhcpd leaves leases in the file which it /knows/ are no longer valid.
So, here is an example:
lease 192.168.66.132 {
starts 4 2009/01/08 23:58:41;
ends 5 2009/01/09 00:00:41;
binding state free;
hardware ethernet 00:e0:81:28:2d:56;
}
lease 192.168.66.133 {
starts 5 2009/01/09 03:17:17;
ends 2 2038/01/19 03:14:06;
binding state active;
next binding state free;
hardware ethernet 00:e0:81:28:2d:57;
}
You can see that 132 is not in use (binding state free) and 133 is
(binding state active). Another possibility is binding state backup,
but that only occurs in a failover config.
A lease can also be abandoned, which means that the DHCP server was
going to assign that IP, but found it was already in use (via ping).
This is all documented in dhcpd.leases(5).
Why are you wanting this?
The DHCP server already re-uses expired leases. Is there a good
reason that you need to check its work? If you're running out of
leases, have you considered lowering the lease time?
Does nmap -sP <start_ip>-<end_ip> do what you need? That'll also
detect machines with static IP addresses.
Re-writing the question
So, given the above, and assuming you still want this, I'm going to
answer this question instead:
Please write a script to find all leases which are either active or
abandoned and determine if there is currently a machine using that IP
address.
And so:
#!/usr/bin/perl
use File::Slurp qw(slurp);
use Data::Dump qw(pp);
use strict;
1 == #ARGV
or die "Usage: $0 dhpcd.leases\n";
my $leases = slurp($ARGV[0]);
$leases =~ s/^#.*\n//mg;
my #leases = split(/lease (\d.+\d.+\d.+\d+) {/, $leases);
shift #leases;
my %lease = #leases;
while (my ($ip, $rec) = each %lease) {
print $ip;
$rec =~ /^\s*abandoned;\s*$/m and print " abandoned";
$rec =~ /^\s*binding state free;\s*$/m and print " free";
$rec =~ /^\s*binding state active;\s*$/m and print " active";
print "\n";
}
This relatively ugly perl script will give you output like:
192.168.66.132 free
192.168.66.133 active
Which should be pretty easy for you to feed to arping.
the problem is, binding state active; does not means, the device is active. To make sure the device is active, we need to ping the devices first. there is no other way we can do it