공인 ip 가져오기는 HttpClient 를 사용하기 때문에 비동기 방식을 사용합니다.
공인 아이피 통신에 실패한 경우 local IP를 호출하여 가져옵니다.
local IP를 가져오는 함수는 기존에 사용했던 함수를 비동기 방식으로 변경해서 사용합니다.
2024.04.02 - [c#] - c# 로컬 ip 가져오기 / c# local ip 가져오기
c# 로컬 ip 가져오기 / local ip 가져오기
로컬 ip 중 version 4를 호출합니다. ip4 를 반환하거나 string.Empty를 반환합니다. 만약 다른 ip 계열을 반환하고 싶다면 foreach 문안의 if문의 AddressFamily 열거형의 다른 주소 체계의 필드를 사용하시면
austar.tistory.com
/// <summary>
/// 공인 ip 가져오기
/// HTTP 요청 만들기는 네트워크 I/O 바인딩된 작업으로 간주됩니다. 동기 HttpClient.Send 메서드가 있지만, 사용해야 할 적절한 이유가 없다면 비동기 API를 대신 사용하는 것이 좋습니다.
/// </summary>
/// <returns></returns>
public static async Task<string> GetPublicIp()
{
try
{
// http 통신을 위한 준비
using HttpClient client = new();
// 해당 주소로 get 비동기 통신
using HttpResponseMessage response = await client.GetAsync("https://ipinfo.io/ip");
// 200 코드를 반환 받았을 경우
if (response.IsSuccessStatusCode)
{
// HttpContent 클래스를 사용하여 요청 본문을 가져온다.
return await response.Content.ReadAsStringAsync();
}
else
{
// 네트워크 오류로 공인 ip 를 가져올 수 없는 경우, 로컬 ip를 반환한다
return await GetLocalIp();
}
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 로컬 ip version 4 호출
/// </summary>
/// <returns></returns>
public static async Task<string> GetLocalIp()
{
return await Task.Run(() =>
{
try
{
// Dns.GetHostName() : 로컬 컴퓨터의 호스트 이름을 가져온다
// Dns.GetHostEntry() : 호스트 이름 또는 IP 주소를 IPHostEntry 인스턴스로 확인한다.
// Dns.GetHostEntry() : address에 지정된 호스트의 주소 정보를 포함하는 IPHostEntry 인스턴스를 반환한다
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
string clientIp = string.Empty;
// IPHostEntry.AddressList : 호스트와 연결된 IP 주소 목록을 가져오거나 설정한다.
foreach (IPAddress addressList in host.AddressList)
{
// IPAddress.AddressFamily IP 주소의 주소 계열을 가져옵니다.
// AddressFamily.InterNetwork : Address for IP version 4.
// 가져온 주소 계열이 ip version 4 일 경우
if (addressList.AddressFamily == AddressFamily.InterNetwork)
{
clientIp = addressList.ToString();
break;
}
}
return clientIp.TrimSafe();
}
catch
{
return string.Empty;
}
});
}
https://learn.microsoft.com/ko-kr/dotnet/api/system.net.http.httpclient?view=net-8.0
HttpClient 클래스 (System.Net.Http)
HTTP 요청을 보내고 URI로 식별된 리소스에서 HTTP 응답을 수신하기 위한 클래스를 제공합니다.
learn.microsoft.com
https://learn.microsoft.com/ko-kr/dotnet/fundamentals/networking/http/httpclient
HttpClient를 사용하여 HTTP 요청 만들기 - .NET
.NET의 HttpClient를 사용하여 HTTP 요청을 만들고 응답을 처리하는 방법을 알아봅니다.
learn.microsoft.com
'c# > helper' 카테고리의 다른 글
| c# ApplicationHighDpiMode 고해상도에서 선명하게 (0) | 2024.04.22 |
|---|---|
| c# WPF 태블릿 스타일러스 입력 비활성 (0) | 2024.04.05 |
| c# 로컬 ip 가져오기 / c# local ip 가져오기 (0) | 2024.04.02 |
| c# 왼쪽부터 문자열 자르기 (0) | 2024.04.02 |
| c# IsNullOrWhiteSpace()을 이용한 trim() 안전하게 사용하기 (0) | 2024.04.02 |