Last active
September 4, 2021 10:50
-
-
Save jbe2277/4b9f5ac0fb3556569960d2e1f3c5bf28 to your computer and use it in GitHub Desktop.
[Xamarin, MAUI] Parse IPAddress provided by iOS NetServiceBrowser (supports IPv4 and IPv6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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