C#获取本地IP地址

public static bool TryGetLocalEndPoint(out IPEndPoint ipEndPoint)
{
    try {
        string localIP = string.Empty;
        using (Socket socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp))
        {
            socket.Connect("www.baidu.com", 80);
            ipEndPoint = socket.LocalEndPoint as IPEndPoint;
            return true;
        }
    }
    catch(SocketException ex) {
        ipEndPoint = null;
        return false;
    }

}
posted @ 2023-06-30 23:43  dewxin  阅读(102)  评论(0编辑  收藏  举报