Many Windows and non-Windows based network devices will respond with their name to a NetBios name request sent on UDP port 137. The following code demonstrates the use of the Socket class to send such a request. The program takes as it's only command line argument the IP address of a target machine. The use of the ReceiveTimeOut socket option is needed to prevent the program from waiting indefinitly should the specified IP address not belong to a machine or should that machine not respond with it's NetBios name.
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPSocketExample
{
class Program
{
// The following byte stream contains the necessary message
// to request a NetBios name from a machine
static byte[] NameRequest = new byte[]{
0x80, 0x94, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4b, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21,
0x00, 0x01 };
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.Out.WriteLine("Usage: xxx.exe [IP Address]");
return ;
}
byte[] receiveBuffer = new byte[1024];
Socket requestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
IPAddress[] addressList = Dns.GetHostAddresses(args[0]);
if (addressList.Length == 0)
{
Console.Out.WriteLine("The requested host could not be found ({0})", args[0]);
return;
}
EndPoint remoteEndpoint = new IPEndPoint(addressList[0],137);
IPEndPoint originEndpoint = new IPEndPoint(IPAddress.Any, 0);
requestSocket.Bind(originEndpoint);
requestSocket.SendTo(NameRequest, remoteEndpoint);
try
{
int receivedByteCount = requestSocket.ReceiveFrom(receiveBuffer, ref remoteEndpoint);
if (receivedByteCount >= 90)
{
Encoding enc = new ASCIIEncoding();
string dnsEntryName = Dns.GetHostByAddress(addressList[0]).HostName;
string deviceName = enc.GetString(receiveBuffer, 57, 16).Trim();
string networkName = enc.GetString(receiveBuffer, 75, 16).Trim();
Console.Out.WriteLine(String.Format( "Request Sent to :{0}\n\r"+
"NetBios Query Result:{1}\r\n"+
"Reverse DNS Lookup :{2}\r\n", args[0],deviceName,dnsEntryName));
}
}
catch (SocketException )
{
Console.Out.WriteLine(String.Format("The device identified by {0} could not be identified by a NetBios name",args[0]));
}
}
}
}