How to Get Ip of All Hosts in Lan

How to get IP of all hosts in LAN?

You'll have to do a ping sweep. There's a Ping class in the System.Net namespace. Example follows. Also this is only possible if your computers don't have firewalls running. If they've got a firewall enabled, there's no way to determine this information short of doing SNMP queries on your switches.

System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply rep = p.Send("192.168.1.1");
if (rep.Status == System.Net.NetworkInformation.IPStatus.Success)
{
//host is active
}

The other issue is to determine how large your network is. In most home situations, your network mask will be 24 bits. This means that its set to 255.255.255.0. If your gateway is 192.168.1.1, this means that valid addresses on your network will be 192.168.1.1 to 192.168.1.254. Here's an IP Calculator to help. You'll have to loop through each address and ping the address using the Ping class and check the PingReply.

If you're just looking for the information and aren't concerned with how you get it, you can use NMap. The command would be as follows

nmap -sP 192.168.1.0/24

EDIT:

As far as speed goes, since you're on a local network, you can cut down the timeout interval considerably as your machines shouldn't take more than 100 milliseconds to reply. You can also use SendAsync to ping them all in parallel. The following program will ping 254 address in under half a second.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace ConsoleApplication1
{
class Program
{
static CountdownEvent countdown;
static int upCount = 0;
static object lockObj = new object();
const bool resolveNames = true;

static void Main(string[] args)
{
countdown = new CountdownEvent(1);
Stopwatch sw = new Stopwatch();
sw.Start();
string ipBase = "10.22.4.";
for (int i = 1; i < 255; i++)
{
string ip = ipBase + i.ToString();

Ping p = new Ping();
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
countdown.AddCount();
p.SendAsync(ip, 100, ip);
}
countdown.Signal();
countdown.Wait();
sw.Stop();
TimeSpan span = new TimeSpan(sw.ElapsedTicks);
Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
Console.ReadLine();
}

static void p_PingCompleted(object sender, PingCompletedEventArgs e)
{
string ip = (string)e.UserState;
if (e.Reply != null && e.Reply.Status == IPStatus.Success)
{
if (resolveNames)
{
string name;
try
{
IPHostEntry hostEntry = Dns.GetHostEntry(ip);
name = hostEntry.HostName;
}
catch (SocketException ex)
{
name = "?";
}
Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, e.Reply.RoundtripTime);
}
else
{
Console.WriteLine("{0} is up: ({1} ms)", ip, e.Reply.RoundtripTime);
}
lock(lockObj)
{
upCount++;
}
}
else if (e.Reply == null)
{
Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip);
}
countdown.Signal();
}
}
}

EDIT: After some use of it myself, I modified the program to output a count of how many IPs responded. There's a const bool that if set to true, will cause the program resolve the host names of the IPs. This significantly slows down the scan, though. (under half a second to 16 seconds) Also found that if the IP address is incorrectly specified (made a typo myself), the reply object can be null, so I handled that.

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

How to get IP addresses of hosts on local network running my program

As mentioned in comments, you need some kind of peer-discovery protocol.

As many multimedia devices, routers etc. use multicast based discovery protocols like SSDP, I created a similar discovery service sample .

Usage is simple. Just use

Discoverer.PeerJoined = ip => Console.WriteLine("JOINED:" + ip);
Discoverer.PeerLeft= ip => Console.WriteLine("LEFT:" + ip);

Discoverer.Start();

All your clients will use the same code.


using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Caching; // add this library from the reference tab
using System.Text;
using System.Threading.Tasks;

namespace SO
{
public class Discoverer
{
static string MULTICAST_IP = "238.212.223.50"; //Random between 224.X.X.X - 239.X.X.X
static int MULTICAST_PORT = 2015; //Random

static UdpClient _UdpClient;
static MemoryCache _Peers = new MemoryCache("_PEERS_");

public static Action<string> PeerJoined = null;
public static Action<string> PeerLeft = null;

public static void Start()
{
_UdpClient = new UdpClient();
_UdpClient.Client.Bind(new IPEndPoint(IPAddress.Any, MULTICAST_PORT));
_UdpClient.JoinMulticastGroup(IPAddress.Parse(MULTICAST_IP));

Task.Run(() => Receiver());
Task.Run(() => Sender());
}

static void Sender()
{
var IamHere = Encoding.UTF8.GetBytes("I AM ALIVE");
IPEndPoint mcastEndPoint = new IPEndPoint(IPAddress.Parse(MULTICAST_IP), MULTICAST_PORT);

while (true)
{
_UdpClient.Send(IamHere, IamHere.Length, mcastEndPoint);
Task.Delay(1000).Wait();
}
}

static void Receiver()
{
var from = new IPEndPoint(0, 0);
while (true)
{
_UdpClient.Receive(ref from);
if (_Peers.Add(new CacheItem(from.Address.ToString(), from),
new CacheItemPolicy() {
SlidingExpiration = TimeSpan.FromSeconds(20),
RemovedCallback = (x) => { if (PeerLeft != null) PeerLeft(x.CacheItem.Key); }
}
)
)
{
if (PeerJoined != null) PeerJoined(from.Address.ToString());
}

Console.WriteLine(from.Address.ToString());
}
}
}
}

Now a little bit about the algorithm:

  • Every client multicasts a packet every seconds.

  • if the receiver(every client has it) gets a packet from an IP that isn't in its cache, it will fire PeerJoined method.

  • Cache will expire in 20 seconds. If a client doesn't receive a packet within that duration from another client in cache, it will fire PeerLeft method.

How to get all ip address in LAN?

This might do the trick for you

foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if(!ip.IsDnsEligible)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// All IP Address in the LAN
}
}
}
}

The Only drawback of this code is that the information returned by instances of UnicastIPAddressInformation is not available for operating systems earlier than Windows XP.

Get IP address from hostname in LAN

Try this

public static void DoGetHostAddresses(string hostname)
{

IPAddress[] ips;

ips = Dns.GetHostAddresses(hostname);

Console.WriteLine("GetHostAddresses({0}) returns:", hostname);

foreach (IPAddress ip in ips)
{
Console.WriteLine(" {0}", ip);
}
}

i got this from http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx

How to find all ip adresses in Lan using TcpClient

I did something like this can you try it :

    private static void ScanNetwork(int port)
{
string GetAddress(string subnet, int i)
{
return new StringBuilder(subnet).Append(i).ToString();
}

Parallel.For(0, 254, async i =>
{
string address = GetAddress("192.168.1.", i);

using (var client = new TcpClient())
{
try
{
await client.ConnectAsync(IPAddress.Parse(address), port).ConfigureAwait(false);

await Task.Delay(5).ConfigureAwait(false);

if (!client.Connected) return;

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Success @{address}");

client.Close();
}
catch (SocketException ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed @{address} Error code: {ex.ErrorCode}");
}
}
});
}

List of IP addresses/hostnames from local network in Python

If by "local" you mean on the same network segment, then you have to perform the following steps:

  1. Determine your own IP address
  2. Determine your own netmask
  3. Determine the network range
  4. Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address).
  5. Use your DNS's reverse lookup to determine the hostname for IP addresses which respond to your scan.

Or you can just let Python execute nmap externally and pipe the results back into your program.



Related Topics



Leave a reply



Submit