Dear I'm developing a c# service which should scan network to detect active snmp devices. I would like to get a result similar to NMAP command results run with Linux, in term of devices founded.
nmap -P0 -v -sU -p 161 192.168.1.0/24
What I have tried:
Just for test, I made a small application to scan open UDP port. First I run a listener into a thread on port 161 and later i run sender. but i was able to get back the response only by 1 device, while NMAP give me back much more devices.
Any suggest?
Thanks in advance,
here you are my code:
UDP listner
<pre>
private void button1_Click(object sender, EventArgs e)
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
int port = int.Parse(txtPort.Text);
bool done = false;
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 161);
UdpClient listener = new UdpClient(groupEP);
string received_data;
byte[] receive_byte_array;
try
{
while (!done)
{
Console.WriteLine("SERVER: Waiting for broadcast");
receive_byte_array = listener.Receive(ref groupEP);
if (!hosts.ContainsKey(groupEP.Address.ToString()) ) {
hosts.Add(groupEP.Address.ToString(), groupEP.Address.ToString());
Console.WriteLine("SERVER: Received a broadcast from {0}", groupEP.Address.ToString());
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}).Start();
}
and here
UDP Sender
<pre>
private void button2_Click(object sender, EventArgs e)
{
new Thread(() =>
{
int port = int.Parse(txtPort.Text);
string message = txtMessage.Text;
Boolean done = false;
Boolean exception_thrown = false;
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse("192.168.1.255");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, port);
while (!done)
{
string text_to_send = message;
if (text_to_send.Length == 0)
{
done = true;
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("CLIENT: sending to address: {0} port: {1}",
sending_end_point.Address,
sending_end_point.Port);
try
{
sending_socket.SendTimeout = 5000;
sending_socket.SendTo(send_buffer, sending_end_point);
}
catch (Exception send_exception)
{
exception_thrown = true;
Console.WriteLine("CLIENT: Exception {0}", send_exception.Message);
}
if (exception_thrown == false)
{
Console.WriteLine("CLIENT: Message has been sent to the broadcast address");
}
else
{
exception_thrown = false;
Console.WriteLine("CLIENT: The exception indicates the message was not sent.");
}
}
}
}).Start();
}
}