Skip to content

Instantly share code, notes, and snippets.

@jbe2277
Last active September 4, 2021 10:50
Show Gist options
  • Save jbe2277/4b9f5ac0fb3556569960d2e1f3c5bf28 to your computer and use it in GitHub Desktop.
Save jbe2277/4b9f5ac0fb3556569960d2e1f3c5bf28 to your computer and use it in GitHub Desktop.
[Xamarin, MAUI] Parse IPAddress provided by iOS NetServiceBrowser (supports IPv4 and IPv6)
private void ServiceAddressResolved(object sender, EventArgs e)
{
var service = (NSNetService)sender;
var addresses = service.Addresses.Select(x => x.ToArray()).ToArray();
var ipAddress = GetIPAddress(addresses.First()); // Consider that resolve might provide multiple IP addresses
// ...
}
private static IPAddress? GetIPAddress(byte[] data)
{
const int ipV4AddressSize = 16;
const int ipV6AddressSize = 28;
if (data.Length != ipV4AddressSize && data.Length != ipV6AddressSize) return null;
bool isIPv4 = data.Length == ipV4AddressSize;
var socketAddress = new SocketAddress(isIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6, data.Length);
for (int i = 2; i < data.Length; i++) socketAddress[i] = data[i]; // First 2 bytes are reserved for AddressFamily
var ep = new IPEndPoint(isIPv4 ? IPAddress.Any : IPAddress.IPv6Any, 0);
return ((IPEndPoint)ep.Create(socketAddress)).Address;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment