NameServiceClient.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* Copyright (C) 2020 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using SMBLibrary.NetBios;
  12. namespace SMBLibrary.Client
  13. {
  14. public class NameServiceClient
  15. {
  16. public static readonly int NetBiosNameServicePort = 137;
  17. private IPAddress m_serverAddress;
  18. public NameServiceClient(IPAddress serverAddress)
  19. {
  20. m_serverAddress = serverAddress;
  21. }
  22. public string GetServerName()
  23. {
  24. NodeStatusRequest request = new NodeStatusRequest();
  25. request.Header.QDCount = 1;
  26. request.Question.Name = "*".PadRight(16, '\0');
  27. NodeStatusResponse response = SendNodeStatusRequest(request);
  28. foreach (KeyValuePair<string, NameFlags> entry in response.Names)
  29. {
  30. NetBiosSuffix suffix = NetBiosUtils.GetSuffixFromMSNetBiosName(entry.Key);
  31. if (suffix == NetBiosSuffix.FileServiceService)
  32. {
  33. return entry.Key;
  34. }
  35. }
  36. return null;
  37. }
  38. private NodeStatusResponse SendNodeStatusRequest(NodeStatusRequest request)
  39. {
  40. UdpClient client = new UdpClient();
  41. IPEndPoint serverEndPoint = new IPEndPoint(m_serverAddress, NetBiosNameServicePort);
  42. client.Connect(serverEndPoint);
  43. byte[] requestBytes = request.GetBytes();
  44. client.Send(requestBytes, requestBytes.Length);
  45. byte[] responseBytes = client.Receive(ref serverEndPoint);
  46. return new NodeStatusResponse(responseBytes, 0);
  47. }
  48. }
  49. }