본문 바로가기
프로그래밍/C#

[C#] localIP / public IP 가져오기

by 뽀도 2021. 3. 23.

localIP, publicIP 가져오기

 

▶ 서버를 개발하다보면 localhost나 127.0.0.1 외에 IP 주소가 필요한 경우가 있다. 

▶ 그때 매번 cmd창 켜서 ipconfig 검색하고, "내 아이피검색" 안해도 아래 코드를 사용하면 편하게 PC의 IP를 가져 올 수 있다. 

 

 

 

 

LocalIP 가져오기

 

public static string GetLocalIP()
{
    string result = string.Empty;

    var host = Dns.GetHostEntry(Dns.GetHostName());

    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            result = ip.ToString();
            break;
        }

        return result;
    }
}

 

 

 

 

 

public IP 가져오기

 

public static string GetPublicIP()
{
    string externalip = new WebClient().DownloadString("http://ipinfo.io/ip").Trim();

    if (string.IsNullOrWhiteSpace(externalip))
    {
        externalip = GetLocalIP();//null경우 Get Internal IP를 가져오게 한다.
    }

    return externalip;
}

 

 

 

반응형

댓글