如何获取主机名的IP地址?

时间:2011-01-27 00:39:10

标签: c# c#-4.0

我正在创建一个连接到本地托管的服务器的客户端,该服务器从服务器获取库存号。如果我使用下面的代码,该程序确实有效,但它的工作方式是获取dns名称所以理论上它只需要www.website.com我无法弄清楚如何让它识别正常的ip为127.0。 0.1或localhost IP:

   IPHostEntry ipHostInfo = Dns.GetHostEntry("www.website.com");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

附件是我尝试解决这个问题,但我不认为我正在接近这个权利,可以在这里看到完整的代码:StockReader Client Code

    public class AsynchronousClient
{

    private const int port = 21;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;

    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 

      //******************ISSUE BEGINS HERE*********************************  
            string sHostName = Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.GetHostEntry(sHostName);
            IPAddress [] ipAddress = ipHostInfo.AddressList; 
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(client, "This is a test<EOF>");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

3 个答案:

答案 0 :(得分:1)

设置ipAddress的值时,可以使用IPAddress.Parse方法传入字符串并检索IPAddress对象,而不是使用域名:

string ip = "127.0.0.1";
IPAddress address = IPAddress.Parse(ipAddress);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

答案 1 :(得分:0)

尝试使用string sHostName = "localhost";

答案 2 :(得分:0)

// Establish the remote endpoint for the socket.  
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, portnumber);

// Create a TCP/IP socket.  
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(remoteEP);