C#에서 현재 컴퓨터의 호스트 이름(Hostname)을 알아내려면 System.Net 네임스페이스에 포함된 Dns.GetHostName() 메서드를 사용하면 됩니다. 이 메서드는 현재 시스템의 호스트 이름을 문자열 형태로 반환합니다.
1. 호스트 이름 가져오기
먼저 Dns.GetHostName() 메서드를 호출하여 호스트 이름을 구합니다.
String hostName = string.Empty;
hostName = Dns.GetHostName();
Console.WriteLine("Hostname: " + hostName);
2. IP 주소 가져오기
호스트 이름을 구했다면, Dns.GetHostEntry() 메서드로 DNS 정보를 조회한 뒤 IPHostEntry.AddressList 속성을 사용해 해당 호스트에 할당된 모든 IP 주소를 가져올 수 있습니다.
IPHostEntry myIP = Dns.GetHostEntry(hostName);
IPAddress[] address = myIP.AddressList;
전체 예제 코드
다음은 호스트 이름과 IP 주소를 함께 출력하는 완전한 C# 프로그램입니다.
using System;
using System.Net;
class Program {
static void Main() {
String hostName = string.Empty;
hostName = Dns.GetHostName();
Console.WriteLine("Hostname: " + hostName);
IPHostEntry myIP = Dns.GetHostEntry(hostName);
IPAddress[] address = myIP.AddressList;
for (int i = 0; i < address.Length; i++) {
Console.WriteLine("IP Address {0} : {1}", i, address[i].ToString());
}
Console.ReadLine();
}
}
코드 설명
- Dns.GetHostName(): 현재 시스템의 호스트 이름을 반환합니다.
- Dns.GetHostEntry(hostName): 지정한 호스트 이름에 대한 DNS 정보를 조회합니다.
- AddressList: 해당 호스트와 연결된 모든 IP 주소를
IPAddress배열 형태로 담고 있습니다.
프로그램을 실행하면 콘솔에 먼저 호스트 이름이 출력되고, 이어서 시스템에 할당된 각 IP 주소가 순서대로 표시됩니다. 하나의 컴퓨터에 여러 네트워크 어댑터나 IPv4·IPv6 주소가 동시에 존재할 수 있으므로, 목록에는 두 개 이상의 IP 주소가 출력될 수도 있습니다.