Friday, May 11, 2007

Obtain all IP Addresses

System.Net namespace provides some functions that I find really useful when it comes to networking. You can use the GetHostName method to retrieve the computer name and GetHostEntry to get all IPs assigned to that computer.

Both Visual Basic.net & C Sharp examples are provided below.

VB.net

Private Function GetIPs() As String

Dim strHostName As String = Dns.GetHostName
Dim myipaddress As IPAddress
Dim strTemp As String = "Host Name: " & strHostName & vbCrLf & "IPs: "
Dim ipHostEntry As IPHostEntry = Dns.GetHostEntry(strHostName)

For Each myipaddress In ipHostEntry.AddressList
strTemp += myipaddress.ToString & ","
Next

Return strTemp.Substring(1, strTemp.Length - 2)

End Function

C#

private string GetIPs()
{
string strHostName = Dns.GetHostName();
string strTemp = "Host Name: " + strHostName + "\r\n" + "IPs: ";

IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);
foreach (IPAddress myipaddress in ipHostEntry.AddressList)
{
strTemp = strTemp + myipaddress + ",";
}
return strTemp.Substring(1, (strTemp.Length - 2));
}

No comments: