简体   繁体   中英

What is right way to get IP address in .Net?

I have two standalone exe's Parent.exe and Child.exe.

Parent.exe opens Child.exe and some operation are performed in child.exe by user then child.exe sends back some processed data to Parent.exe. Both exe's stays on same machine

The communication between Child.Exe and Parent.Exe is being done through TCP IP (Socket Programming). For this we need to calculate the Local IP Address, we used to calculate it in the following way :-

       string hostname = Dns.GetHostName();

       IPHostEntry ipEntry = Dns.GetHostEntry(hostname);
       IPAddress[] addr = ipEntry.AddressList;
       string FinalIpAddrs = addr[0]

Everything worked fine at XP but with Windows 7 we are facing problem. The below line return Mac Address what is the right way to do it, so that it works on XP and Win7 both?

       string FinalIpAddrs = addr[0]

Oh, those wh program and do not know.

  • You do NOT need to know an IP Address, use 127.0.0.1, which is a local loopback address. SImple like that - it is there for exactly that reason.

  • Consider being efficient. If that is all same machine, the usage of TCP is bad. Use named pipes, which are a windows integrated commmunciation mechanism that CAN work cross machine, but on the same machine it uses shared memory which is a LOT more efficient than TCP.

Why not just use IPAddress.Loopback (or IPv6Loopback )?

The loopback addresses are designed for communications entirely on the same host.


I'm also guessing that where you say:

The below line return Mac Address

What you actually mean is that it's returning an IPv6 address. There's no way that that code should be able to return a MAC Address.

Is there a specific requirement NOT to use 127.0.0.1? If no, then I'd just use it without any calculations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM