123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Sockets;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net.NetworkInformation;
- using System.Runtime.InteropServices;
- using System.Configuration;
- using System.Net.Http;
- public static class IpHelper
- {
- private static string _localIp;
- /// <summary>
- /// 获取本地IP
- /// </summary>
- /// <returns></returns>
- public static string GetLocalIp()
- {
- if (!string.IsNullOrWhiteSpace(_localIp))
- {
- return _localIp;
- }
- string localIP = null;
- try
- {
- foreach (string item in ConfigurationManager.AppSettings.Keys)
- {
- if (item == "LocalIP")
- {
- localIP = ConfigurationManager.AppSettings["LocalIP"].Trim();//优先使用本地配置的IP
- }
- }
- if (!string.IsNullOrWhiteSpace(localIP))
- return localIP;
- }
- catch
- {
- }
- try
- {
- using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
- {
- socket.Connect("8.8.8.8", 65530);
- IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
- localIP = endPoint.Address.ToString();
- return localIP;
- }
- }
- catch
- {
- }
- return "127.0.0.1";
- }
- public static void SetLocalIp(string localIp)
- {
- _localIp = localIp;
- }
- }
|