Get the server name and ip address in C# 2010
I want to get the IP address of the server. The following code comes from:
public static void DoGetHostEntry(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
MessageBox.Show("GetHostEntry({0}) returns:"+ hostname);
foreach (IPAddress ip in host.AddressList)
{
MessageBox.Show(" {0}"+ ip.ToString());
}
}
This code must know the name of the server computer.
AddressFamily in System.Net.IPAddress
System.Net.IPAddress i;
string HostName = i.AddressFamily.ToString();
Error ------------->Use of unassigned local variable 'i'
How can I get the name of the server computer?
First of all, you need to figure out for yourself that error(unassigned local variable) and learn why it is coming(it is very basic), before looking for some magical code that will do the job for you.
And secondly, there is no magical code. I am no socket programmer but it seems to me that in your application running on the client machines, you need to hardcode the name of your server. If you don't want to do that, program in such a way that only your server machine will listen on a particular port and all client machines will listen on a different port. Thus, each machine in the LAN can enumerate over the available machines and establish/determine the client server connection/relation for the first time. and that approach is still very ugly unless you are writing a virus or something.
To get the host name you can do the following:
If you want the hostname and (first IPv4) IP of your computer use the following:
The name and the ip will hold the info for the local computer.
The server could then send out the ip via a udp multicast and the client on the network would just join a known multicast address that is not specific to the server.
multicast example.