1

Below code can get us IPAddress using Environment.MachineName but Environment.MachineName can return maximum upto 15 characters, what if the value is more than 15 characters?

string IP_Address = Dns.GetHostByName(Environment.MachineName).AddressList[0].toString();
Cœur
  • 37,241
  • 25
  • 195
  • 267
Yaswanth
  • 59
  • 1
  • 10
  • 1
    Use an empty string instead (it returns local computer information). Also note that you shouldn't pick first entry...it may return multiple addresses (both for physical networks and for logical ones). – Adriano Repetti Dec 03 '15 at 07:54
  • I din get what you are saying repetti, can you please write the statement you are talking about? – Yaswanth Dec 03 '15 at 09:40

1 Answers1

2

You could use Dns.GetHostName(). See: https://msdn.microsoft.com/en-us/library/system.net.dns.gethostname(v=vs.110).aspx

System.Net.Dns.GetHostName() returns the computer's TCP/IP based hostname. By adding a domain suffix to the hostname you can resolve your computer's IP address across LANs / on the internet.

Source: Difference between SystemInformation.ComputerName, Environment.MachineName, and Net.Dns.GetHostName

You can find the domain suffix using this: https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipinterfaceproperties.dnssuffix(v=vs.110).aspx

Community
  • 1
  • 1
usselite
  • 846
  • 7
  • 24
  • But attackers can spoof the DNS Host name so Dns.GetHostName() is not reliable. Is there any other better way? – Yaswanth Dec 03 '15 at 09:39
  • I am afraid you probably have to validate the legitimacy of the DNS Host name. Perhaps this will help you: https://sujithin.wordpress.com/2011/03/19/misused-authentication-using-gethostname-asp-net/ – usselite Dec 03 '15 at 10:22