Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets

Public Module NetworkFeatures

    Public Function GetIPFromHost(hostName As String) As IPAddress
        Return Dns.GetHostAddresses(hostName).FirstOrDefault(Function(n) n.AddressFamily = AddressFamily.InterNetwork)
    End Function

    Public Function GetHostFromIP(ip As String)
        Return Dns.GetHostEntry(ip)?.HostName
    End Function

    Public Function GetLocalIPInformations() As UnicastIPAddressInformation
        Dim addr As UnicastIPAddressInformation = Nothing

        For Each adapter As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces
            If addr Is Nothing AndAlso adapter.OperationalStatus = OperationalStatus.Up AndAlso adapter.NetworkInterfaceType <> NetworkInterfaceType.Tunnel AndAlso adapter.NetworkInterfaceType <> NetworkInterfaceType.Loopback Then
                For Each uni As UnicastIPAddressInformation In adapter.GetIPProperties.UnicastAddresses
                    If addr Is Nothing AndAlso uni.Address.AddressFamily = AddressFamily.InterNetwork Then
                        addr = uni
                    End If
                Next
            End If
        Next

        Return addr
    End Function

    Public Function GetLocalIPAddress() As IPAddress
        Return GetLocalIPInformations()?.Address
    End Function

    Public Function GetLocalIPv4Mask() As IPAddress
        Return GetLocalIPInformations()?.IPv4Mask
    End Function

    Public Function GetLocalBoradcastIP(ipInfo As UnicastIPAddressInformation) As IPAddress
        Dim ip As IPAddress = Nothing
        Dim myIPBytes As Byte() = ipInfo.Address.GetAddressBytes
        Dim subnetBytes As Byte() = ipInfo.IPv4Mask.GetAddressBytes
        Dim broadcastBytes As Byte() = New Byte(myIPBytes.Length - 1) {}

        For i As Integer = 0 To subnetBytes.Length - 1
            broadcastBytes(i) = myIPBytes(i) Or Not subnetBytes(i)
        Next

        ip = New IPAddress(broadcastBytes)

        Return ip
    End Function

End Module
