Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# 4.0 - Get the server name and ip address in C# 2010

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get the host name you can do the following:

string name = System.Net.Dns.GetHostName();

If you want the hostname and (first IPv4) IP of your computer use the following:

string name = System.Net.Dns.GetHostName();
host = System.Net.Dns.GetHostEntry(name);
System.Net.IPAddress ip = host.AddressList.Where(n => n.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...