[RESOLVED] Getting the real IP address
Hello.
In a WinForm application, if you want to get the IP address of the machine the code is running on (for instance, to log in the database what the IP address is when a user deletes a record), I would use this code:
Code:
Dim xEntry As System.Net.IPHostEntry = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName)
Dim ipAddr As Net.IPAddress() = xEntry.AddressList
lblIP.Text = ipAddr(0).ToString()
While the code works, and it returns the correct IP address (for example: 140.139.138.137), Visual Studio doesn't like that code, and tells you that GetHostByName is obsolete, and needs to be replaced with GetHostEntry.
But if i do that, then i get back something that does not look like an IP address: fe80::28ba:e091:1056:949f%11
So my question is, if i'm not supposed to use GetHostByName because it's been replaced by GetHostEntry, how come GetHostEntry doesn't give me the IP address?
.
Re: Getting the real IP address
That IS an IP address, you may not be used to it because it is IPv6. You are used to IPv4, if you want the IPv4 address, you can use the following code:
Code:
Dim entry = Dns.GetHostEntry(System.Net.Dns.GetHostName())
For Each address In entry.AddressList
If address.AddressFamily = AddressFamily.InterNetwork Then
'//IPv4 (you are used to this format)
Console.WriteLine(address.ToString())
Exit For
End If
Next
Re: Getting the real IP address
That makes a lot more sense. I cleaned up your code a little bit (completed the variable declarations), but otherwise it works. Thanks. :thumb:
.
Re: Getting the real IP address
Quote:
Originally Posted by
MrGTI
That makes a lot more sense. I cleaned up your code a little bit (completed the variable declarations), but otherwise it works. Thanks. :thumb:
.
You are on VS2010 and you don't use Option Infer? It's great, you should turn it on.
Re: Getting the real IP address
Quote:
Originally Posted by
ForumAccount
You are on VS2010 and you don't use Option Infer? It's great, you should turn it on.
I normally don't want to use type inference (although I always leave Option Infer on) because I like to know exactly what type to use/declare before hand and code will be much easier to follow when you spell it out... Take the line below for example:
Dim x = someType.GetCollection
When someone reads the code line above, unless the person is extremely familiar with that someType type and knows exactly what GetCollection function returns, he/she will have a hard time knowing what x will be.