C#获取本地IP
2026年6月21日通过创建 UDP 套接字连接到外部地址,可以获取当前网络接口的本地 IP:
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
Console.WriteLine("本地 IP: " + endPoint.Address.ToString());
}
}
}