C# 取得本机 IP

通常情况下,一台电脑不止一个 IP,因此需要考虑枚举出所有的 IP.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace tmpshowip
{
    class Program
    {
        static void Main(string[] args)
        {
            string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
            for (int i = 0; i < Dns.GetHostByName(hostName).AddressList.Length; i++)
            {
                // Get the IP  
                string myIP = Dns.GetHostByName(hostName).AddressList[i].ToString();
                Console.WriteLine("My IP Address is :" + myIP);
            }
            Console.ReadKey();
        }
    }
}

参考:

1.https://www.codeproject.com/questions/399318/how-to-get-user-ip-address-using-csharp

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注