Skip to content

Commit

Permalink
(#39) Add hostname support to MPDConnectionService
Browse files Browse the repository at this point in the history
  • Loading branch information
Difegue committed Sep 15, 2023
1 parent 9f9ab0c commit d11811d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
21 changes: 21 additions & 0 deletions Sources/Stylophone.Common/Helpers/Miscellaneous.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using SkiaSharp;
using System;
using System.IO;
using System.Net;

namespace Stylophone.Common.Helpers
{
Expand Down Expand Up @@ -83,5 +84,25 @@ public static string EscapeFilename(string fileName)
}
return fileName.Replace(".", "002E");
}

public static IPEndPoint GetIPEndPointFromHostName(string hostName, int port, bool throwIfMoreThanOneIP)
{
var addresses = System.Net.Dns.GetHostAddresses(hostName);
if (addresses.Length == 0)
{
throw new ArgumentException(
"Unable to retrieve address from specified host name.",
"hostName"
);
}
else if (throwIfMoreThanOneIP && addresses.Length > 1)
{
throw new ArgumentException(
"There is more that one IP address to the specified host.",
"hostName"
);
}
return new IPEndPoint(addresses[0], port); // Port gets validated here.
}
}
}
13 changes: 10 additions & 3 deletions Sources/Stylophone.Common/Services/MPDConnectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Stylophone.Common.Interfaces;
using MpcNET.Commands.Reflection;
using Stylophone.Localization.Strings;
using Stylophone.Common.Helpers;

namespace Stylophone.Common.Services
{
Expand Down Expand Up @@ -134,10 +135,16 @@ public void Disconnect()
private async Task TryConnecting(CancellationToken token)
{
if (token.IsCancellationRequested) return;
if (!IPAddress.TryParse(_host, out var ipAddress))
throw new Exception("Invalid IP address");

_mpdEndpoint = new IPEndPoint(ipAddress, _port);
if (!IPAddress.TryParse(_host, out var ipAddress))
{
// Maybe it's a hostname? Try getting an IP from it nonetheless
_mpdEndpoint = Miscellaneous.GetIPEndPointFromHostName(_host, _port, false);
}
else
{
_mpdEndpoint = new IPEndPoint(ipAddress, _port);
}

_statusConnection = await GetConnectionInternalAsync(token);

Expand Down

0 comments on commit d11811d

Please sign in to comment.