在控制台应用程序中获取IP地址

17 c# console-application

我想从控制台应用程序中找出我的IP地址.

我习惯使用Request.ServerVariables集合和/或Web应用程序Request.UserHostAddress.

如何在控制台应用程序中完成?

Cod*_*ker 27

最简单的方法如下:

using System;
using System.Net;


namespace ConsoleTest
{
    class Program
    {
        static void Main()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;

            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
            }
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可能应该包含指向您复制此代码的页面的链接,您不觉得吗?我的意思是,这是谷歌的首批成果之一. (2认同)