This class represents a NetBIOS over TCP/IP address.
This class represents a NetBIOS over TCP/IP address. Under normal conditions, users of jCIFS need not be concerned with this class as name resolution and session services are handled internally by the smb package.

Applications can use the methods getLocalHost, getByName, and getAllByAddress to create a new NbtAddress instance. This class is symmetric with System.Net.IPAddress .

About NetBIOS: The NetBIOS name service is a dynamic distributed service that allows hosts to resolve names by broadcasting a query, directing queries to a server such as Samba or WINS. NetBIOS is currently the primary networking layer for providing name service, datagram service, and session service to the Microsoft Windows platform. A NetBIOS name can be 15 characters long and hosts usually registers several names on the network. From a Windows command prompt you can see what names a host registers with the nbtstat command.

 C:\>nbtstat -a 192.168.1.15 NetBIOS Remote Machine Name Table Name               Type         Status --------------------------------------------- JMORRIS2        <00>  UNIQUE      Registered BILLING-NY      <00>  GROUP       Registered JMORRIS2        <03>  UNIQUE      Registered JMORRIS2        <20>  UNIQUE      Registered BILLING-NY      <1E>  GROUP       Registered JMORRIS         <03>  UNIQUE      Registered MAC Address = 00-B0-34-21-FA-3B 

The hostname of this machine is JMORRIS2. It is a member of the group(a.k.a workgroup and domain) BILLING-NY. To obtain an System.Net.IPAddress for a host one might do:

 InetAddress addr = NbtAddress.getByName( "jmorris2" ).getInetAddress(); 

From a UNIX platform with Samba installed you can perform similar diagnostics using the nmblookup utility.

Beispiel #1
0
        static NbtAddress()
        {
            IPAddress localInetAddress;
            string    localHostname;
            Name      localName;

            AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
                                                         , Forever));
            localInetAddress = Client.laddr;
            if (localInetAddress == null)
            {
                try
                {
                    localInetAddress = Extensions.GetAddressByName("127.0.0.1");
                }
                catch (UnknownHostException)
                {
                }
            }
            localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
            if (string.IsNullOrEmpty(localHostname))
            {
                byte[] addr = localInetAddress.GetAddressBytes();

                /*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
                 *  (int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
                 *                      (int)(0xFF))), 2);*/
                localHostname = "JCIFS_127_0_0_1";
            }
            localName = new Name(localHostname, unchecked (0x00), Config.GetProperty("jcifs.netbios.scope"
                                                                                     , null));
            Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
                                       , false, false, true, false, UnknownMacAddress);
            CacheAddress(localName, Localhost, Forever);
        }
        /// <exception cref="System.IO.IOException"></exception>
        internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex)
        {
            if (@in.Read(buffer, bufferIndex, Length) != Length)
            {
                throw new IOException("unexpected EOF reading netbios retarget session response");
            }
            int addr = ReadInt4(buffer, bufferIndex);

            bufferIndex     += 4;
            _retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
            _retargetPort    = ReadInt2(buffer, bufferIndex);
            return(Length);
        }
		/// <exception cref="System.IO.IOException"></exception>
		internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
			)
		{
			if (@in.Read(buffer, bufferIndex, Length) != Length)
			{
				throw new IOException("unexpected EOF reading netbios retarget session response");
			}
			int addr = ReadInt4(buffer, bufferIndex);
			bufferIndex += 4;
			_retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
			_retargetPort = ReadInt2(buffer, bufferIndex);
			return Length;
		}
Beispiel #4
0
        internal static void CacheAddress(Name hostName, NbtAddress addr)
        {
            if (CachePolicy == 0)
            {
                return;
            }
            long expiration = -1;

            if (CachePolicy != Forever)
            {
                expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
            }
            CacheAddress(hostName, addr, expiration);
        }
Beispiel #5
0
 /// <summary>Retrieve all addresses of a host by it's address.</summary>
 /// <remarks>
 /// Retrieve all addresses of a host by it's address. NetBIOS hosts can
 /// have many names for a given IP address. The name and IP address make the
 /// NetBIOS address. This provides a way to retrieve the other names for a
 /// host with the same IP address.
 /// </remarks>
 /// <param name="addr">the address to query</param>
 /// <exception cref="UnknownHostException">if address cannot be resolved</exception>
 public static NbtAddress[] GetAllByAddress(NbtAddress addr)
 {
     try
     {
         NbtAddress[] addrs = Client.GetNodeStatus(addr);
         CacheAddressArray(addrs);
         return(addrs);
     }
     catch (UnknownHostException)
     {
         throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
                                                                                     HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
                                                                                                                                                == 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
                                        + addr.GetHostAddress());
     }
 }
        /// <exception cref="UnknownHostException"></exception>
        internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr)
        {
            //Log.Out("NameSerciceClient.GetAllByName");

            int n;
            NameQueryRequest  request  = new NameQueryRequest(name);
            NameQueryResponse response = new NameQueryResponse();

            request.Addr        = addr ?? NbtAddress.GetWinsAddress();
            request.IsBroadcast = (request.Addr == null ||
                                   request.Addr.ToString() == Baddr.ToString());

            if (request.IsBroadcast)
            {
                request.Addr = Baddr;
                n            = RetryCount;
            }
            else
            {
                request.IsBroadcast = false;
                n = 1;
            }
            do
            {
                try
                {
                    Send(request, response, RetryTimeout);
                }
                catch (IOException ioe)
                {
                    if (_log.Level > 1)
                    {
                        Runtime.PrintStackTrace(ioe, _log);
                    }
                    throw new UnknownHostException(ioe);
                }
                if (response.Received && response.ResultCode == 0)
                {
                    return(response.AddrEntry);
                }
            }while (--n > 0 && request.IsBroadcast);
            throw new UnknownHostException();
        }
Beispiel #7
0
        internal static NbtAddress GetByName(Name name)
        {
            lock (typeof(Lmhosts))
            {
                NbtAddress result = null;
                try
                {
                    if (Filename != null)
                    {
                        FilePath f = new FilePath(Filename);
                        long     lm;
                        if ((lm = f.LastModified()) > _lastModified)
                        {
                            _lastModified = lm;
                            Tab.Clear();
                            _alt = 0;

                            //path -> fileStream
                            //Populate(new FileReader(f));
                            Populate(new FileReader(new FileStream(f, FileMode.Open)));
                        }
                        result = (NbtAddress)Tab[name];
                    }
                }
                catch (FileNotFoundException fnfe)
                {
                    if (_log.Level > 1)
                    {
                        _log.WriteLine("lmhosts file: " + Filename);
                        Runtime.PrintStackTrace(fnfe, _log);
                    }
                }
                catch (IOException ioe)
                {
                    if (_log.Level > 0)
                    {
                        Runtime.PrintStackTrace(ioe, _log);
                    }
                }
                return(result);
            }
        }
Beispiel #8
0
 private static void CacheAddress(Name hostName, NbtAddress addr, long expiration)
 {
     if (CachePolicy == 0)
     {
         return;
     }
     lock (AddressCache)
     {
         CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
         if (entry == null)
         {
             entry = new CacheEntry(hostName, addr, expiration);
             AddressCache.Put(hostName, entry);
         }
         else
         {
             entry.Address    = addr;
             entry.Expiration = expiration;
         }
     }
 }
        /// <exception cref="UnknownHostException"></exception>
        internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
        {
            //Log.Out("NameSerciceClient.GetNodeStatus");

            int n;
            int srcHashCode;
            NodeStatusRequest  request;
            NodeStatusResponse response;

            response     = new NodeStatusResponse(addr);
            request      = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked (0x00), null));
            request.Addr = addr.GetInetAddress();
            n            = RetryCount;

            while (n-- > 0)
            {
                try
                {
                    Send(request, response, RetryTimeout);
                }
                catch (IOException ioe)
                {
                    if (_log.Level > 1)
                    {
                        Runtime.PrintStackTrace(ioe, _log);
                    }
                    throw new UnknownHostException(ioe);
                }
                if (response.Received && response.ResultCode == 0)
                {
                    srcHashCode = request.Addr.GetHashCode();
                    for (int i = 0; i < response.AddressArray.Length; i++)
                    {
                        response.AddressArray[i].HostName.SrcHashCode = srcHashCode;
                    }
                    return(response.AddressArray);
                }
            }
            throw new UnknownHostException();
        }
Beispiel #10
0
		/// <exception cref="SharpCifs.Smb.SmbException"></exception>
		private static NtlmChallenge Interrogate(NbtAddress addr)
		{
			UniAddress dc = new UniAddress(addr);
			SmbTransport trans = SmbTransport.GetSmbTransport(dc, 0);
			if (Username == null)
			{
				trans.Connect();
                if (SmbTransport.LogStatic.Level >= 3)
				{
                    SmbTransport.LogStatic.WriteLine("Default credentials (jcifs.smb.client.username/password)"
						 + " not specified. SMB signing may not work propertly." + "  Skipping DC interrogation."
						);
				}
			}
			else
			{
				SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default
					);
				ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null);
			}
			return new NtlmChallenge(trans.Server.EncryptionKey, dc);
		}
 /// <exception cref="UnknownHostException"></exception>
 internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
 {
     int n;
     int srcHashCode;
     NodeStatusRequest request;
     NodeStatusResponse response;
     response = new NodeStatusResponse(addr);
     request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null));
     request.Addr = addr.GetInetAddress();
     n = RetryCount;
     while (n-- > 0)
     {
         try
         {
             Send(request, response, RetryTimeout);
         }
         catch (IOException ioe)
         {
             if (_log.Level > 1)
             {
                 Runtime.PrintStackTrace(ioe, _log);
             }
             throw new UnknownHostException(ioe);
         }
         if (response.Received && response.ResultCode == 0)
         {
             srcHashCode = request.Addr.GetHashCode();
             for (int i = 0; i < response.AddressArray.Length; i++)
             {
                 response.AddressArray[i].HostName.SrcHashCode = srcHashCode;
             }
             return response.AddressArray;
         }
     }
     throw new UnknownHostException();
 }
Beispiel #12
0
        private int ReadNodeNameArray(byte[] src, int srcIndex)
        {
            int start = srcIndex;

            AddressArray = new NbtAddress[_numberOfNames];
            string n;
            int    hexCode;
            string scope = _queryAddress.HostName.Scope;
            bool   groupName;
            int    ownerNodeType;
            bool   isBeingDeleted;
            bool   isInConflict;
            bool   isActive;
            bool   isPermanent;
            int    j;
            bool   addrFound = false;

            try
            {
                for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
                {
                    for (j = srcIndex + 14; src[j] == unchecked (0x20); j--)
                    {
                    }
                    n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
                                                  );
                    hexCode   = src[srcIndex + 15] & unchecked (0xFF);
                    groupName = ((src[srcIndex + 16] & unchecked (0x80)) == unchecked (0x80))
                                    ? true
                                    : false;
                    ownerNodeType  = (src[srcIndex + 16] & unchecked (0x60)) >> 5;
                    isBeingDeleted = ((src[srcIndex + 16] & unchecked (0x10)) == unchecked (0x10))
                                    ? true
                                    : false;
                    isInConflict = ((src[srcIndex + 16] & unchecked (0x08)) == unchecked (0x08))
                                    ? true
                                    : false;
                    isActive = ((src[srcIndex + 16] & unchecked (0x04)) == unchecked (0x04))
                                    ? true
                                    : false;
                    isPermanent = ((src[srcIndex + 16] & unchecked (0x02)) == unchecked (0x02))
                                    ? true
                                    : false;
                    if (!addrFound &&
                        _queryAddress.HostName.HexCode == hexCode &&
                        (_queryAddress.HostName == NbtAddress.UnknownName ||
                         _queryAddress.HostName.name.Equals(n)))
                    {
                        if (_queryAddress.HostName == NbtAddress.UnknownName)
                        {
                            _queryAddress.HostName = new Name(n, hexCode, scope);
                        }
                        _queryAddress.GroupName            = groupName;
                        _queryAddress.NodeType             = ownerNodeType;
                        _queryAddress.isBeingDeleted       = isBeingDeleted;
                        _queryAddress.isInConflict         = isInConflict;
                        _queryAddress.isActive             = isActive;
                        _queryAddress.isPermanent          = isPermanent;
                        _queryAddress.MacAddress           = _macAddress;
                        _queryAddress.IsDataFromNodeStatus = true;
                        addrFound       = true;
                        AddressArray[i] = _queryAddress;
                    }
                    else
                    {
                        AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope),
                                                         _queryAddress.Address,
                                                         groupName,
                                                         ownerNodeType,
                                                         isBeingDeleted,
                                                         isInConflict,
                                                         isActive,
                                                         isPermanent,
                                                         _macAddress);
                    }
                }
            }
            catch (UnsupportedEncodingException)
            {
            }
            return(srcIndex - start);
        }
Beispiel #13
0
 internal NodeStatusResponse(NbtAddress queryAddress)
 {
     this._queryAddress = queryAddress;
     RecordName         = new Name();
     _macAddress        = new byte[6];
 }
Beispiel #14
0
        /// <exception cref="UnknownHostException"></exception>
        internal virtual NbtAddress GetByName(Name name, IPAddress addr)
        {
            int n;

            NameQueryRequest  request  = new NameQueryRequest(name);
            NameQueryResponse response = new NameQueryResponse();

            if (addr != null)
            {
                request.Addr        = addr;
                request.IsBroadcast = (addr.GetAddressBytes()[3] == unchecked (unchecked (0xFF)));
                n = RetryCount;
                do
                {
                    try
                    {
                        Send(request, response, RetryTimeout);
                    }
                    catch (IOException ioe)
                    {
                        if (_log.Level > 1)
                        {
                            Runtime.PrintStackTrace(ioe, _log);
                        }
                        throw new UnknownHostException(ioe);
                    }
                    if (response.Received && response.ResultCode == 0 &&
                        response.IsResponse)
                    {
                        int last = response.AddrEntry.Length - 1;
                        response.AddrEntry[last].HostName.SrcHashCode = addr.GetHashCode();
                        return(response.AddrEntry[last]);
                    }
                }while (--n > 0 && request.IsBroadcast);
                throw new UnknownHostException();
            }
            for (int i = 0; i < _resolveOrder.Length; i++)
            {
                try
                {
                    switch (_resolveOrder[i])
                    {
                    case ResolverLmhosts:
                    {
                        NbtAddress ans = Lmhosts.GetByName(name);
                        if (ans != null)
                        {
                            ans.HostName.SrcHashCode = 0;
                            // just has to be different
                            // from other methods
                            return(ans);
                        }
                        break;
                    }

                    case ResolverWins:
                    case ResolverBcast:
                    {
                        if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName &&
                            name.HexCode != unchecked (0x1d))
                        {
                            request.Addr        = NbtAddress.GetWinsAddress();
                            request.IsBroadcast = false;
                        }
                        else
                        {
                            request.Addr        = Baddr;
                            request.IsBroadcast = true;
                        }
                        n = RetryCount;
                        while (n-- > 0)
                        {
                            try
                            {
                                Send(request, response, RetryTimeout);
                            }
                            catch (IOException ioe)
                            {
                                if (_log.Level > 1)
                                {
                                    Runtime.PrintStackTrace(ioe, _log);
                                }
                                throw new UnknownHostException(ioe);
                            }
                            if (response.Received && response.ResultCode == 0 &&
                                response.IsResponse)
                            {
                                response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode();
                                return(response.AddrEntry[0]);
                            }
                            if (_resolveOrder[i] == ResolverWins)
                            {
                                break;
                            }
                        }
                        break;
                    }
                    }
                }
                catch (IOException)
                {
                }
            }
            throw new UnknownHostException();
        }
Beispiel #15
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Send(NameServicePacket request, NameServicePacket response,
                                   int timeout)
        {
            int nid = 0;
            int max = NbtAddress.Nbns.Length;

            if (max == 0)
            {
                max = 1;
            }

            lock (response)
            {
                while (max-- > 0)
                {
                    try
                    {
                        lock (_lock)
                        {
                            request.NameTrnId = GetNextNameTrnId();
                            nid = request.NameTrnId;
                            response.Received = false;
                            _responseTable.Put(nid, response);
                            EnsureOpen(timeout + 1000);
                            int requestLenght = request.WriteWireFormat(_sndBuf, 0);
                            _socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
                            if (_log.Level > 3)
                            {
                                _log.WriteLine(request);
                                Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
                            }
                        }
                        if (_waitResponse)
                        {
                            long start = Runtime.CurrentTimeMillis();
                            while (timeout > 0)
                            {
                                Runtime.Wait(response, timeout);
                                if (response.Received && request.QuestionType == response.RecordType)
                                {
                                    return;
                                }
                                response.Received = false;
                                timeout          -= (int)(Runtime.CurrentTimeMillis() - start);
                            }
                        }
                    }
                    catch (Exception ie)
                    {
                        throw new IOException(ie.Message);
                    }
                    finally
                    {
                        //Sharpen.Collections.Remove(responseTable, nid);
                        if (_waitResponse)
                        {
                            _responseTable.Remove(nid);
                        }
                    }
                    if (_waitResponse)
                    {
                        lock (_lock)
                        {
                            if (NbtAddress.IsWins(request.Addr) == false)
                            {
                                break;
                            }
                            if (request.Addr == NbtAddress.GetWinsAddress())
                            {
                                NbtAddress.SwitchWins();
                            }
                            request.Addr = NbtAddress.GetWinsAddress();
                        }
                    }
                }
            }
        }
Beispiel #16
0
		/// <summary>Retrieve all addresses of a host by it's address.</summary>
		/// <remarks>
		/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
		/// have many names for a given IP address. The name and IP address make the
		/// NetBIOS address. This provides a way to retrieve the other names for a
		/// host with the same IP address.
		/// </remarks>
		/// <param name="addr">the address to query</param>
		/// <exception cref="UnknownHostException">if address cannot be resolved</exception>
		public static NbtAddress[] GetAllByAddress(NbtAddress addr)
		{
			try
			{
				NbtAddress[] addrs = Client.GetNodeStatus(addr);
				CacheAddressArray(addrs);
				return addrs;
			}
			catch (UnknownHostException)
			{
				throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
					HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
					 == 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
					 + addr.GetHostAddress());
			}
		}
Beispiel #17
0
		static NbtAddress()
		{
			IPAddress localInetAddress;
			string localHostname;
			Name localName;
			AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
				, Forever));
			localInetAddress = Client.laddr;
			if (localInetAddress == null)
			{
				try
				{
                    localInetAddress = Extensions.GetAddressByName("127.0.0.1");
				}
				catch (UnknownHostException)
				{

				}
			}
			localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
			if (string.IsNullOrEmpty(localHostname))
			{
				byte[] addr = localInetAddress.GetAddressBytes();
				
                /*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
                    (int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
					(int)(0xFF))), 2);*/
			    localHostname = "JCIFS_127_0_0_1";
			}
			localName = new Name(localHostname, unchecked(0x00), Config.GetProperty("jcifs.netbios.scope"
				, null));
			Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
				, false, false, true, false, UnknownMacAddress);
			CacheAddress(localName, Localhost, Forever);
		}
Beispiel #18
0
 internal CacheEntry(Name hostName, NbtAddress address, long expiration)
 {
     this.HostName   = hostName;
     this.Address    = address;
     this.Expiration = expiration;
 }
Beispiel #19
0
		/// <exception cref="System.IO.IOException"></exception>
		internal static void Populate(StreamReader r)
		{
			string line;
            BufferedReader br = new BufferedReader((InputStreamReader)r);
			while ((line = br.ReadLine()) != null)
			{
				line = line.ToUpper().Trim();
				if (line.Length == 0)
				{
				}
				else
				{
					if (line[0] == '#')
					{
						if (line.StartsWith("#INCLUDE "))
						{
							line = Runtime.Substring(line, line.IndexOf('\\'));
							string url = "smb:" + line.Replace('\\', '/');
							if (_alt > 0)
							{
								try
								{
									Populate(new InputStreamReader(new SmbFileInputStream(url)));
								}
								catch (IOException ioe)
								{
									_log.WriteLine("lmhosts URL: " + url);
									Runtime.PrintStackTrace(ioe, _log);
									continue;
								}
								_alt--;
								while ((line = br.ReadLine()) != null)
								{
									line = line.ToUpper().Trim();
									if (line.StartsWith("#END_ALTERNATE"))
									{
										break;
									}
								}
							}
							else
							{
								Populate(new InputStreamReader(new SmbFileInputStream(url)));
							}
						}
						else
						{
							if (line.StartsWith("#BEGIN_ALTERNATE"))
							{
								_alt++;
							}
							else
							{
								if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
								{
									_alt--;
									throw new IOException("no lmhosts alternate includes loaded");
								}
							}
						}
					}
					else
					{
						if (char.IsDigit(line[0]))
						{
							char[] data = line.ToCharArray();
							int ip;
							int i;
							int j;
							Name name;
							NbtAddress addr;
							char c;
							c = '.';
							ip = i = 0;
							for (; i < data.Length && c == '.'; i++)
							{
								int b = unchecked(0x00);
								for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
								{
									b = b * 10 + c - '0';
								}
								ip = (ip << 8) + b;
							}
							while (i < data.Length && char.IsWhiteSpace(data[i]))
							{
								i++;
							}
							j = i;
							while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
							{
								j++;
							}
							name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null
								);
							addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
								, NbtAddress.UnknownMacAddress);
							Tab.Put(name, addr);
						}
					}
				}
			}
		}
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Send(NameServicePacket request,
                                   NameServicePacket response,
                                   int timeout)
        {
            //Log.Out("NameSerciceClient.Send - Start");

            int nid = 0;
            int max = NbtAddress.Nbns.Length;

            if (max == 0)
            {
                max = 1;
            }

            lock (response)
            {
                this._isActive = true;

                while (max-- > 0)
                {
                    try
                    {
                        lock (_lock)
                        {
                            request.NameTrnId = GetNextNameTrnId();
                            nid = request.NameTrnId;

                            response.Received = false;
                            _responseTable.Put(nid, response);

                            //Log.Out($"NameSerciceClient.Send - timeout = {timeout}");
                            EnsureOpen(timeout + 1000);

                            int    requestLenght = request.WriteWireFormat(_sndBuf, 0);
                            byte[] msg           = new byte[requestLenght];
                            Array.Copy(_sndBuf, msg, requestLenght);

                            _socketSender.SetSocketOption(SocketOptionLevel.Socket,
                                                          SocketOptionName.Broadcast,
                                                          request.IsBroadcast
                                                            ? 1
                                                            : 0);

                            _socketSender.SendTo(msg, new IPEndPoint(request.Addr, _lport));
                            //Log.Out("NameSerciceClient.Send - Sended");

                            if (_log.Level > 3)
                            {
                                _log.WriteLine(request);
                                Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
                            }
                        }

                        if (_waitResponse)
                        {
                            long start      = Runtime.CurrentTimeMillis();
                            var  isRecieved = false;
                            var  startTime  = DateTime.Now;
                            while (timeout > 0)
                            {
                                Runtime.Wait(response, timeout);
                                if (response.Received && request.QuestionType == response.RecordType)
                                {
                                    //return;
                                    isRecieved = true;
                                    break;
                                }
                                response.Received = false;
                                timeout          -= (int)(Runtime.CurrentTimeMillis() - start);

                                //if (timeout <= 0)
                                //{
                                //    Log.Out($"NameSerciceClient.Send Timeout! - {(DateTime.Now - startTime).TotalMilliseconds} msec");
                                //}
                            }

                            if (isRecieved)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception ie)
                    {
                        if (_waitResponse)
                        {
                            _responseTable.Remove(nid);
                        }

                        //Log.Out("NameSerciceClient.Send - IOException");

                        throw new IOException(ie.Message);
                    }
                    finally
                    {
                        if (_waitResponse)
                        {
                            _responseTable.Remove(nid);
                        }
                    }

                    if (_waitResponse)
                    {
                        lock (_lock)
                        {
                            if (NbtAddress.IsWins(request.Addr) == false)
                            {
                                break;
                            }
                            if (request.Addr == NbtAddress.GetWinsAddress())
                            {
                                NbtAddress.SwitchWins();
                            }
                            request.Addr = NbtAddress.GetWinsAddress();
                        }
                    }
                }

                this._isActive = false;
                //Log.Out("NameSerciceClient.Send - Normaly Ended.");
            }
        }
		private int ReadNodeNameArray(byte[] src, int srcIndex)
		{
			int start = srcIndex;
			AddressArray = new NbtAddress[_numberOfNames];
			string n;
			int hexCode;
			string scope = _queryAddress.HostName.Scope;
			bool groupName;
			int ownerNodeType;
			bool isBeingDeleted;
			bool isInConflict;
			bool isActive;
			bool isPermanent;
			int j;
			bool addrFound = false;
			try
			{
				for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
				{
					for (j = srcIndex + 14; src[j] == unchecked(0x20); j--)
					{
					}
					n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
						);
					hexCode = src[srcIndex + 15] & unchecked(0xFF);
					groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
					ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5;
					isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false;
					isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : false;
					isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04)) ? true : false;
					isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02)) ? true : false;
					if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName
						 == NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n)))
					{
						if (_queryAddress.HostName == NbtAddress.UnknownName)
						{
							_queryAddress.HostName = new Name(n, hexCode, scope);
						}
						_queryAddress.GroupName = groupName;
						_queryAddress.NodeType = ownerNodeType;
						_queryAddress.isBeingDeleted = isBeingDeleted;
						_queryAddress.isInConflict = isInConflict;
						_queryAddress.isActive = isActive;
						_queryAddress.isPermanent = isPermanent;
						_queryAddress.MacAddress = _macAddress;
						_queryAddress.IsDataFromNodeStatus = true;
						addrFound = true;
						AddressArray[i] = _queryAddress;
					}
					else
					{
						AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
							, groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent, 
							_macAddress);
					}
				}
			}
			catch (UnsupportedEncodingException)
			{
			}
			return srcIndex - start;
		}
		internal NodeStatusResponse(NbtAddress queryAddress)
		{
			this._queryAddress = queryAddress;
			RecordName = new Name();
			_macAddress = new byte[6];
		}
Beispiel #23
0
		internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration
			)
		{
			if (CachePolicy == 0)
			{
				return;
			}
			lock (AddressCache)
			{
				CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
				if (entry == null)
				{
					entry = new CacheEntry(hostName, addr, expiration);
					AddressCache.Put(hostName, entry);
				}
				else
				{
					entry.Address = addr;
					entry.Expiration = expiration;
				}
			}
		}
Beispiel #24
0
			internal CacheEntry(Name hostName, NbtAddress address, long expiration)
			{
				this.HostName = hostName;
				this.Address = address;
				this.Expiration = expiration;
			}
Beispiel #25
0
		internal static void CacheAddress(Name hostName, NbtAddress addr)
		{
			if (CachePolicy == 0)
			{
				return;
			}
			long expiration = -1;
			if (CachePolicy != Forever)
			{
				expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
			}
			CacheAddress(hostName, addr, expiration);
		}
Beispiel #26
0
        /// <exception cref="System.IO.IOException"></exception>
        internal static void Populate(StreamReader r)
        {
            string         line;
            BufferedReader br = new BufferedReader((InputStreamReader)r);

            while ((line = br.ReadLine()) != null)
            {
                line = line.ToUpper().Trim();
                if (line.Length == 0)
                {
                }
                else
                {
                    if (line[0] == '#')
                    {
                        if (line.StartsWith("#INCLUDE "))
                        {
                            line = Runtime.Substring(line, line.IndexOf('\\'));
                            string url = "smb:" + line.Replace('\\', '/');
                            if (_alt > 0)
                            {
                                try
                                {
                                    Populate(new InputStreamReader(new SmbFileInputStream(url)));
                                }
                                catch (IOException ioe)
                                {
                                    _log.WriteLine("lmhosts URL: " + url);
                                    Runtime.PrintStackTrace(ioe, _log);
                                    continue;
                                }
                                _alt--;
                                while ((line = br.ReadLine()) != null)
                                {
                                    line = line.ToUpper().Trim();
                                    if (line.StartsWith("#END_ALTERNATE"))
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                Populate(new InputStreamReader(new SmbFileInputStream(url)));
                            }
                        }
                        else
                        {
                            if (line.StartsWith("#BEGIN_ALTERNATE"))
                            {
                                _alt++;
                            }
                            else
                            {
                                if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
                                {
                                    _alt--;
                                    throw new IOException("no lmhosts alternate includes loaded");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (char.IsDigit(line[0]))
                        {
                            char[]     data = line.ToCharArray();
                            int        ip;
                            int        i;
                            int        j;
                            Name       name;
                            NbtAddress addr;
                            char       c;
                            c  = '.';
                            ip = i = 0;
                            for (; i < data.Length && c == '.'; i++)
                            {
                                int b = unchecked (0x00);
                                for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
                                {
                                    b = b * 10 + c - '0';
                                }
                                ip = (ip << 8) + b;
                            }
                            while (i < data.Length && char.IsWhiteSpace(data[i]))
                            {
                                i++;
                            }
                            j = i;
                            while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
                            {
                                j++;
                            }
                            name = new Name(Runtime.Substring(line, i, j), unchecked (0x20), null
                                            );
                            addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
                                                  , NbtAddress.UnknownMacAddress);
                            Tab.Put(name, addr);
                        }
                    }
                }
            }
        }
Beispiel #27
0
        internal NameServiceClient(int lport, IPAddress laddr)
        {
            this._lport = lport;
            this.laddr  = laddr ?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault();

            try
            {
                Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255"));
            }
            catch (Exception ex)
            {
            }

            _sndBuf = new byte[SndBufSize];
            _rcvBuf = new byte[RcvBufSize];


            if (string.IsNullOrEmpty(Ro))
            {
                if (NbtAddress.GetWinsAddress() == null)
                {
                    _resolveOrder    = new int[2];
                    _resolveOrder[0] = ResolverLmhosts;
                    _resolveOrder[1] = ResolverBcast;
                }
                else
                {
                    _resolveOrder    = new int[3];
                    _resolveOrder[0] = ResolverLmhosts;
                    _resolveOrder[1] = ResolverWins;
                    _resolveOrder[2] = ResolverBcast;
                }
            }
            else
            {
                int[]           tmp = new int[3];
                StringTokenizer st  = new StringTokenizer(Ro, ",");
                int             i   = 0;
                while (st.HasMoreTokens())
                {
                    string s = st.NextToken().Trim();
                    if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
                    {
                        tmp[i++] = ResolverLmhosts;
                    }
                    else
                    {
                        if (Runtime.EqualsIgnoreCase(s, "WINS"))
                        {
                            if (NbtAddress.GetWinsAddress() == null)
                            {
                                if (_log.Level > 1)
                                {
                                    _log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
                                                   );
                                }
                                continue;
                            }
                            tmp[i++] = ResolverWins;
                        }
                        else
                        {
                            if (Runtime.EqualsIgnoreCase(s, "BCAST"))
                            {
                                tmp[i++] = ResolverBcast;
                            }
                            else
                            {
                                if (Runtime.EqualsIgnoreCase(s, "DNS"))
                                {
                                }
                                else
                                {
                                    // skip
                                    if (_log.Level > 1)
                                    {
                                        _log.WriteLine("unknown resolver method: " + s);
                                    }
                                }
                            }
                        }
                    }
                }
                _resolveOrder = new int[i];
                Array.Copy(tmp, 0, _resolveOrder, 0, i);
            }
        }
Beispiel #28
0
		internal static void CacheAddressArray(NbtAddress[] addrs)
		{
			if (CachePolicy == 0)
			{
				return;
			}
			long expiration = -1;
			if (CachePolicy != Forever)
			{
				expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
			}
			lock (AddressCache)
			{
				for (int i = 0; i < addrs.Length; i++)
				{
					CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName
						);
					if (entry == null)
					{
						entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration);
						AddressCache.Put(addrs[i].HostName, entry);
					}
					else
					{
						entry.Address = addrs[i];
						entry.Expiration = expiration;
					}
				}
			}
		}