Search code examples
c#iplan

How to get IP of computer on lan if you have the computers name, using c#


I'm currently writing a C# program to connect one computer to another on lan. I have the computer name of the receiving computer but the ip is dynamic so it will change from time to time.

How would I get the lan IP adress of the receiving computer? (the one that goes like 192.168.1.# )


Solution

  • Assuming based on your assumption you are looking for the first IPv4 ip address you can use the following:

    String name = "Name";
    IPHostEntry ipHostInfo = Dns.GetHostEntry(name);            
    // OR you can get the name of the current computer using 
    // IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());                
    
    // Get the first IPv4 address
    IPAddress ip = ipHostInfo.AddressList.Where(n => n.AddressFamily == AddressFamily.InterNetwork).First();