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
323 views
in Technique[技术] by (71.8m points)

c# - Resolve HostName to IP

I have been through a lot of googling for this, I found a lot of examples none of which was working for me. This is a simple issue which I feel has a simple answer without defining new classesmodules etc...

My code is this :

Console.WriteLine ("Please enter an IP address or hostname");
string host = Console.ReadLine ();
***IP = resolved "host"*** 
Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);    
s.Connect (IP, 80);
s.close();

How do I actually resolve the IP variable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can simply use the DNS class to do so:

IPHostEntry hostEntry;

hostEntry= Dns.GetHostEntry(host);

//you might get more than one ip for a hostname since 
//DNS supports more than one record

if (hostEntry.AddressList.Length > 0)
{
      var ip = hostEntry.AddressList[0];
      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
      s.Connect(ip, 80);
}

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

...