Home > Software design >  How to save all ip addresses connected to the network in a text file
How to save all ip addresses connected to the network in a text file

Time:10-13

I would like to create an alert software for employees without outsourcing for security reasons. I found a way to send alerts from cmd with msg command, I didn't test this code but I generated it from Microsoft site, if there is any error please let me know

msg @allip.txt "test"

For IP list, I found a solution using arp -a using cmd but I have to clear the extra info in the file like this, the problem is that if I leave the extra info in the text the code doesn't work

Interface: 192.168.1.140 --- 0x3
  Internet Address      Physical Address      Type
  192.168.1.1           00-00-00-00-00-00     dynamic   
  192.168.1.61          00-00-00-00-00-00     dynamic   
  192.168.1.255         00-00-00-00-00-00     static    
  ...

Is there a way to save only the internet address table

CodePudding user response:

To extract all the cached IP addresses - which is what arp.exe /a reports - use the following:

  • Note: Judging by the linked docs, these cached addresses, stored along with their "their resolved Ethernet or Token Ring physical addresses", with a separate table maintained for each network adapter, are the IP addresses the computer at hand has actively talked to in the current OS session, which is not the same as the complete set of computers connected to the network.
    To scan an entire subnet for reachable IP addresses, consider a third-party function such as Ping-Subnet.
((arp /a) -match '^\s \d').ForEach({ (-split $_)[0] })

To save to a file, say ips.txt, append > ips.txt or | Set-Content ips.txt.

Note:

  • In Windows PowerShell, you'll get different character encodings by these file-saving methods (UTF-16 LE ("Unicode") for > / ANSI for Set-Content)

  • In PowerShell (Core) 7 , you'll get BOM-less UTF-8 files by (consistent) default.

Use Set-Content's -Encoding parameter to control the encoding explicitly.

Explanation:

  • -match '^\s \d' filters the array of lines output by arp /a to include only those starting with (^) at least one ( ) whitespace char. (\), followed by a decimal digit (\d) - this limits the output lines to the lines showing cache-table entries.

  • .ForEach() executes a script block ({ ... }) for each matching line.

  • The unary form of -split, the string splitting operator, splits each matching line into an array of fields by whitespace, and index [0] returns the first such field.

  • Related