Resolves the hostname to its IP address - CSharp System.Net

CSharp examples for System.Net:IP Address

Description

Resolves the hostname to its IP address

Demo Code


using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using System;/*  w w  w. j ava 2  s.  co m*/

public class Main{
        /// <summary>
        /// Resolves the hostname to its IP address
        /// </summary>
        /// <param name="host"> Hostname to resolve (string)</param>
        /// <returns> The host's IP address (string)</returns>
        /// <exception cref="System.Net.Sockets.SocketException"></exception>
        public static string Hostname2IP(string host)
        {
            string ip = null;

            try
            {
                ip = Dns.GetHostEntry(host).AddressList[0].ToString();
            }

            catch (System.Net.Sockets.SocketException sEx)
            {
                ip = sEx.Message;
            }

            catch (ArgumentException aEx)
            {
                ip = aEx.Message;
            }

            catch (Exception e)
            {
                ip = e.Message;
            }

            return ip;
        }
}

Related Tutorials