Reputation: 953
I have been looking over socket implementation and ran across a few ways of implementing them. However I am confused as to why some examples create extra variables to accomplish the same task.
IPHostEntry ipHost = Dns.GetHostEntry("");
IPAddress ipAddr = ipHost.AddressList[0];
ServerSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ServerSocket.Connect(hostName, 56);
I managed to get the above code collapsed down into two lines. Other than the ability to enumerate IP Addresses, is there another benefit to the code above?
ServerSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
ServerSocket.Connect(hostName, 56);
Thank you in advance for your help.
Upvotes: 1
Views: 487
Reputation: 171178
The intention of the first snippet is to automatically choose between IPv4 and IPv6. The first snippet probably has a bug. If there are multiple adapters (which is normal) an arbitrary address family will be chosen. Maybe IPv6 will be chosen and the connection will fail because the target of the connect call does not support IPv4.
Use the second version.
Also, this difference is not about "variables". It is about different semantics. You can arrange the variables as you see fit.
Upvotes: 2
Reputation: 155
The:
IPHostEntry ipHost = Dns.GetHostEntry("");
IPAddress ipAddr = ipHost.AddressList[0];
is giving you your local Ip address. Well to clarify.. it is giving you the first one.
The GetHostEntry method queries a DNS server for the IP address that is associated with a host name or IP address.
When an empty string is passed as the host name, this method returns the IPv4 addresses of the local host.
The reason for the AddressList[0] is because a machine may have multiple local Ip addresses.
Upvotes: 2