Search code examples
c#tcpuwpwindows-10-iot-coredhcp

ConnectionRefused in windows 10 IoT


I've created an DHCP server and I've added a TCP server. When I send a message at address IPv4 of the DHCP server, the client answer with: ConnectionRefused.

I've set the property to true

DataSocket = new DatagramSocket();
DataSocket.Control.MulticastOnly = true;

This code running to boot of the app UWP:

private void Start()
{
  if (this.StatusButton.Content.ToString().Equals(AVVIA))
  {
    this.ViewModel.Action = "AVVIO DEL SERVER DHCP IN CORSO...";
    RunServer();
    this.StatusButton.Content = UPDATE;
    Task.Run(async () => 
    {
      await Task.Delay(DELAY);
      Server = new Server();
      Server.StartServer();
     });
  }

  ... ... ...

private void RunServer()
{
  IPAddress iPAddress;

  DhcpServer = new ScaemDhcp.DhcpServer();
  iPAddress = new IPAddress(new byte[] { 192, 168, 1, 101 });
  DhcpServer.Run(iPAddress, DNS, SUB_MASK, SERVER_IDENTIFIER, ROUTER_IP);
}
public void Run(IPAddress iPAddress, string dns, string subnetMask, string serverIdentifier, string routerIP)
{
  var server = new Dhcp(iPAddress);
  server.ServerName = dns;
  server.BroadcastAddress = IPAddress.Broadcast.ToString();
  server.OnDataReceived += (sender, dhcpRequest) =>
  {
    try
    {
      var type = dhcpRequest.GetMsgType();
      var ip = iPAddress;
      var replyOptions = new DhcpReplyOptions();
      replyOptions.SubnetMask = IPAddress.Parse(subnetMask);
      replyOptions.DomainName = server.ServerName;
      replyOptions.ServerIdentifier = IPAddress.Parse(serverIdentifier);
      replyOptions.RouterIP = IPAddress.Parse(routerIP);
      replyOptions.DomainNameServers = new IPAddress[]
      {IPAddress.Parse("8.8.8.8"), IPAddress.Parse("8.8.4.4")};

      if (type == DhcpMsgType.DHCPDISCOVER)
      {
        dhcpRequest.SendDHCPReply(DhcpMsgType.DHCPOFFER, ip, replyOptions);
      }
      if (type == DhcpMsgType.DHCPREQUEST)
      {
        dhcpRequest.SendDHCPReply(DhcpMsgType.DHCPACK, ip, replyOptions);
      }
    }
    catch (Exception e)
    { }
 };
 server.Start();
}

... ...

public async void StartServer()
{
  try
  {
    var streamSocketListener = new StreamSocketListener();

    streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;

    await streamSocketListener.BindServiceNameAsync(PORT.ToString());
   }
   catch (Exception ex)
   {
       ... ...

Solution

  • From comment by @Michale Xu - MSFT

    @Nicolò, I have given a response on MSDN forum about the similar issue.