Reputation: 1774
I'm a little confuse about getting the ip address of a PC. I have a winforms application running in multiples pc. The application in certain circunstances must send messages to the other apps. To do that I write to the database the infomation about the pc that is running the app, among the data is the IP Address. The idea is to use WCF to comunicate and broadcast messages to running applications. So, the problem is how can I get the working Ip Address. Image a notebook with an ethernet ip address, a wi fi address, and a vmware address. Which of them do i have to choose?
Here is the code i use. But in the case of the notebook it is returning the vmware address, and it is useless.
private String GetMyIp()
{
String ipAddress =
System.Net.Dns.GetHostEntry(
System.Net.Dns.GetHostName())
.AddressList.First(i => i.AddressFamily.Equals(
System.Net.Sockets.AddressFamily.InterNetwork))
.ToString();
return ipAddress;
}
The main idea is to get the ip address which has a connection. Hope be clear.
Thanks in Advance.
Upvotes: 0
Views: 156
Reputation: 5233
There are several things you need to consider when enumerate the active network connection. if you have wifi adapter and LAN connection and both are active , which you would like the running application to use ?
why not using a good practice of central WCF publish-subsribe method, let the running client to request the central WCF service and probably on the WCF server end to store the EndPoint address ?
Upvotes: 1
Reputation: 17868
Well unless you make a connection its a lot of work for your computer to determine which card its going to use.. or did use.
Heres the way I did it.. I made a connection then asked, what it used to do it, actually I used part of your code, it certainly seems to work
Also, of course the other end of the connection can also check the remote (eg client) address in a similar manner..
class Program
{
static void Main(string[] args)
{
TcpClient t = new TcpClient("www.microsoft.com", 80);
Console.WriteLine(GetMyIp(t.Client.LocalEndPoint.AddressFamily));
t.Close();
}
static private String GetMyIp(AddressFamily addr)
{
String ipAddress = System.Net.Dns.GetHostEntry(
System.Net.Dns.GetHostName()
)
.AddressList.First(i => i.AddressFamily.Equals(addr)).ToString();
return ipAddress;
}
}
Upvotes: 1