Get host name from IP address

does anyone have any simple C# code that can do this?
pwpaust
0
pwpaust
8/8/2006 10:02:51 AM
asp.net.getting-started 91979 articles. 3 followers. Follow

15 Replies
1294 Views

Similar Articles

[PageSpeed] 35

Try this.  It's a simple page that looks up both IP and name.  I've put in some data to test with, but you can enter your own text!

 

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Net" %>

<!

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<

script runat="server">

protected string DNSLookup(string domain)

{

string result = string.Empty;

try

{

IPHostEntry ipHe = Dns.GetHostEntry(domain);

IPAddress[] ipAddresses = ipHe.AddressList;

foreach (IPAddress ip in ipAddresses)

result += ip + Environment.NewLine;

return result;

}

catch (System.Exception ex)

{

return ex.Message;

}

}

protected string DnsIpLookup(IPAddress ip)

{

try

{

IPHostEntry ipHe = Dns.GetHostEntry(ip);

return ipHe.HostName;

}

catch (System.Exception ex)

{

return ex.Message;

}

}

protected void lnkGetIpFromDns_Click(object sender, EventArgs e)

{

txtResult.Text = DNSLookup(txtDomainName.Text);

}

protected void lnkGetDomainNameFromIp_Click(object sender, EventArgs e)

{

txtResult.Text = DnsIpLookup(IPAddress.Parse(txtIP.Text));

}

</

script>

<

html xmlns="http://www.w3.org/1999/xhtml">

<

head id="Head1" runat="server">

<title>DNS Lookup</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtDomainName" runat="server" Columns="60">www.microsoft.com</asp:TextBox><asp:LinkButton

ID="lnkGetIpFromDns" runat="server" OnClick="lnkGetIpFromDns_Click">Get IP address(es) from DNS name</asp:LinkButton>

</div>

<div>

<asp:TextBox ID="txtIP" runat="server" Columns="20">207.46.199.30</asp:TextBox><asp:LinkButton

ID="lnkGetDomainNameFromIp" runat="server" OnClick="lnkGetDomainNameFromIp_Click">Get Domain Name from IP</asp:LinkButton>

</div>

<div>

<asp:TextBox ID="txtResult" runat="server" Columns="60" ReadOnly="True" Rows="20"

TextMode="MultiLine"></asp:TextBox>

</div>

</form>

</body>

</html>


If it was easy, everybody would be doing it.
0
sbyard
8/8/2006 9:21:45 PM

Thank you for replying...

 

When i meant easy..I meant..one person has "Dns.Resolve" another has "System.Net.IPhostEntry"

 

and neither work...or wont compile in vs2k5

 

But I will fiddle with yours as yours both compiles in vs and works in the browser :)

 

Thanks again


pwpaust
0
pwpaust
8/8/2006 10:07:39 PM

  Look at the below code. The only thing this doesn't do is try/catch exceptions. So if you have a domain that doesn't resolve it's going to throw an exception. You decide where and how you want to catpture the exception using try{} catch(Exception ex)  {}
    protected void Page_Load(object sender, EventArgs e)
    {
		String		FirstIP			= ResolveHost("google.com");
		if (FirstIP!=null)
		{
			Response.Write("google.com resolved to " + FirstIP);
		}
		else 
		{
			Response.Write("Could not resolve google.com");
		}
    }
    public String	ResolveHost(String name)
    {
		System.Net.IPHostEntry		TmpEntry	= System.Net.Dns.GetHostEntry(name);
		if (TmpEntry.AddressList.Length>0)
		{
			return TmpEntry.AddressList[0].ToString();
		}
		else 
		{
			return null;
		}
    }
 
0
Volcano_88101
8/9/2006 1:56:47 AM

thank you for that code.......

 

i would not think that it would not "not be able"....(how is the for proper english) to resolve an ip...hmmm 

 

i will have to think more


pwpaust
0
pwpaust
8/9/2006 2:13:53 AM
Lots of reasons why it could fail. Domain is invalid, domain has expired, the DNS servers responsible for the domain are down, etc. Network issue. Gotta prepare for everything :-D
0
Volcano_88101
8/9/2006 2:22:55 AM
nah your absolutly right, it would be foolish and arrogant of me not to think of reasons why it would fail
pwpaust
0
pwpaust
8/9/2006 3:16:29 AM

Which would be better for this example?

 

 A property, a function or a method?

 

if it was in a class(dll), and you just needed to call it when ever you wanted it? 


pwpaust
0
pwpaust
8/9/2006 3:22:02 AM
I would make it a static method in a class.  This way you can resuse it over and over simply by adding a reference to the dll in your web project or application. And then use it like normally without a class instance.
0
Volcano_88101
8/9/2006 2:16:46 PM

I wanted to look futher into this static word and dug up this URL

http://msdn2.microsoft.com/en-us/library/98f28cdx.aspx

by the look of that example you still have to create a class instance, and a static will not return anything.....it only modifies that which is in its own class.

 

do you have any examples so i can futher read into this? and perhaps be able to see your point of view clearer?

 

thanks

 


pwpaust
0
pwpaust
8/9/2006 10:12:15 PM
 
// To do most things with a class you have to have an instance of the class. 

BmwM5Car MyCar = new BmwM5Car();
MyCar.Start();

public class BmwM5Car : Car
{
	public void Start()
	{
	}
	public static GetManual ReturnManual()
        {
		return NewBmwOwnerManual();
        }
}

// To start the car you have to have an instance of the class. 
// Now to get a manual for the BMW we don't need to actually own it.
// This method is marked as static and we can just say 
BmwM5Car.GetManual(); 
// notice how we don't have a an instance to access this method.
// the static method is primarily useful for several things
// #1 for  little helper methods 
// #2 for any method that does not require an instnace, rare but as you program more you will see a need for them. 
 
0
Volcano_88101
8/10/2006 2:47:23 AM
ah! thank you, that was a very clear explanation...Thank you for that..
pwpaust
0
pwpaust
8/10/2006 3:23:26 AM

what is IpHostEntry ?

Ganesh@nilgris

 


Jai Ganesh. J , GSD ,India

Please Mark As Answer If my reply helped you.
0
Ganesh
8/10/2006 5:01:28 AM

Ah I have to answer it!

 

My first real ASP.Net respondes where I have at least some idea about what the heck I am talking about! so feel honoured! Mabye because  I have spent the last week building my very first class and this IpHostEntry was the worse one of them

 

On the internet you have an IP.. with is like a phone number for your computer (eg 127.0.0.1 (yes i know that is the loop back ip for a computer))

 

and you can look up the host IP name that is on the comput

with the IpHostEntry

say for example you log all your visitors in a database and you want to know where they come from, if you pass thier IP into that IpHostEntry it will most likely give you their ISP and an idea of which country they came from!(neat huh?)

 

MSDN  - the official - defines it like this  "Resolves a host name or IP address to an IPHostEntry instance. "

its a member of the DNS class...

 

other then that i proudly admit that I dont know how it works :)

 

I hope this is right(if anyone feels its wrong the please point out my mistake so i can have a better understanding) and I hope it answers your question!

 

 

 


pwpaust
0
pwpaust
8/10/2006 5:43:35 AM

I am a developer, and not an IP expert at all, but if you want to know more, I know that there are some pretty thick books on IP out there!

To give you a clue on how all of this works though, try disconnecting your PC from the network when running my code above, and see if you get any results.

The Microsoft network classes do not contain a list of the world's DNS - but they do know where to go and look them up.  Most of us would be concerned with our local networks at home (10.x.x.x and 192.x.x.x), but there a bigger world out there, and that is what IP is all aout really


If it was easy, everybody would be doing it.
0
sbyard
8/10/2006 8:17:17 AM

have to agree with you there....books the size of  encyclopedia's..

I took a look at one while doing my network diploma and the guy said you had to learn all of it

and my brain said "oh...darn..."...but in a more colourful way...:)


pwpaust
0
pwpaust
8/10/2006 9:32:18 AM
Reply:

Similar Artilces:

Is there a way to get IP/Host name given the MAC address?
------_=_NextPart_001_01C19DA2.7BFEE650 Content-Type: text/plain; charset="Windows-1255" > Hi, > > Does anybody know's a way to get a Host name > If I have a Mac address both in pc and sun? > (it's the same as RARP but I don't know how to do it using command line ) > > THX > > ------_=_NextPart_001_01C19DA2.7BFEE650-- 1. SUN without DNS: arp -a 2. SUN with DNS: arp -a; nslookup hostname For Example: % arp -a | grep '00:55:' Net to Media Table Device IP Address Mask Flags...

Get client IP address [Not Host] in C# .NET web services
I create one web service using c# .net and in this web service I want to get an IP address for client. I check thousend of article but that is not working, let me give you one example System.Web.HttpContext.Current.Request.UserHostAddress; System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; This is gives me IP but that my server ip where I put my web service but I want to get my client IP address. Can someone help me with this.http://www.codegroups.com/blog/ You can try: string ip; ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR"); i...

How Do I get rid of \\ ( ie\\ipp//:ip address/ipp/printer) out of the start of my printer name
Hi, How Do I get rid of \\ out of the start of my printer name, I think this is stopping me printing to some printers with certain drivers(HP driver don't seem to mind). If I set printers up manual I do not have this problem and the driver works with the printer, but if I use the automated iprint way it adds \\ to the start of the printer name and it hangs my spooler file. Michael, It appears that in the past few days you have not received a response to your posting. That concerns us, and has triggered this automated reply. Has your problem been resolved? If not, you might ...

POST GET GET GET GET... WTH?
Hi, I'm at a loss to explain this... I have an ASPX page that I can't always navigate to. When I developed the app (it's Starter Kit Portal-based), I did it on my LAN and have had no trouble accessing the page. However, upon deployment, I see the following behavior: 1. POST request goes out looking for MyForm.aspx 2. GET request for MyForm.aspx 3. GET request for MyForm.aspx 4. ... X. GET request Sometimes, the page finally loads. Other times, it just ends up blank. Many times, it doesn't load at ALL the first POST - I just get a "The pa...

How to get Hostname, IP address, port number, DB name, instance name using Query
As we know, normally we connect to a sybase server by just identifying the node name and interfaces file and necessary properties, but currently I want to get Host-name, IP address, port number, DB name, instance name of connected server out after connection created. Does any one how to use query to do so? Does sybase provide such functionality? Seems oracle can do so... If there is no query, does sybase provides any API which can implement this? Thanks! instance name: select @@servername [assumes the DBA has defined a local entry in syservers] db name: select db_name() [can...

Getting NIC to get a dynamic IP address from Cable Modem
Does anyone know how to get my NW 6 server to get a dynamic IP address from a cable/DSL modem? Thanks, Kevin DHCPCLNT name=board_name Add /INETCFG to the end of that to have DHCPCLNT update your INETCFG information for you. After it does that, you'll probably need to manually enable Dynamic NAT on the interface. bd NSC Volunteer SysOp ...

How to get IP address/name of the machine
Hi all, I have a requirement to find out IP address/name of the machine to which a given windows user is currently logged on. Is that possible with C#? If anyone has came across sample code please guide me to appropriate resource. Blog: SEO Articles Website: Search Engine Ranking Are you looking for this? Request.UserHostAddress()   Jef Claes~~~~~~~~~~Visit my blog Hi, Please try to use my code: public static string IPAddress { get { string userIP; HttpRequest Request = HttpContext....

Get domain name from IP address
 Hi all,          I want to convert an Ip address to corresponding domain name if any. Do i really need to use some third party components like IP2location .. Guys Please help..   thanks in advanceplease click 'Mark as Answer' if my post helped you. http://forums.asp.net/p/1039283/1443326.aspx#1443326TUFAN01MAN HostName = System.Net.Dns.GetHostName(); IPAddres = System.Net.Dns.GetHostAddresses(HostName).GetValue(0).ToString();Thanks,AdamPlease "Mark as Answer" if this has helped you.  The above link is ...

How to get IP address or name of the server?
I need to get the IP address or name of the server that runs my asp.net application. Which class, method should I use? Thanks! Try this: Request.ServerVariables["SERVER_NAME"]Darrell Norton, MVPDarrell Norton's BlogPlease mark this post as answered if it helped you! Thank you very much. I tried "SERVER_NAME", but it gives me more info than I need. I used Request.ServerVariables["HTTP_HOST"] instead. ...

Get IP address from network interface name
Hello! I have been using the TNTFirewall component (NTSet) to retreive the network devices of my computer. I get a lot of information för each device eg. NTFireWall.Connections[I].Name, NTFireWall.Connections[I].DeviceName, NTFireWall.Connections[I].GuidId. What I can't find is the currently assigned IP address of each device (if available). How can I get the current IP address assigned to these connections using the above properties? The values are as an example: Name = 'Anslutning till lokalt nätverk' DeviceName = 'Attansic L1 Gigabit Ethernet...

Lookup IP Address to get domain name
Hi I have a datagrid which has a list of IP Addresses in it, I would like to resolve the IP address to show its fully qualified domain name (if found) in another column of the datagrid. Is this possible?  Is there a web service i can use, or is this functionality built into .net 2.0?Thanks in advance Check out this article:http://semichaos.com/articles/aspnet1/iptohost.aspx Darrell Norton, MVPDarrell Norton's BlogPlease mark this post as answered if it helped you! hi,here is some information for you ,hope it helpshttp://semichaos.com/articles/aspnet1/iptohost.aspx...

get IP Address _ Server Name
Hi , All Does anyone know how to get IP Address of Server Name ? Im using PB9.0 and SQL Server 2000 We have four servers and all the same servername(the same SQLCA.servername), just different IP Address . I would like to get IP address to know what server the user has connected . Thanks for helping! ---== Posted via the PFCGuide Web Newsreader ==--- http://www.pfcguide.com/_newsgroups/group_list.asp You do a winsock getaddrinfo call: http://msdn2.microsoft.com/en-us/library/ms738520.aspx There's also a GetAddrInfoEx call that might work better (it shoul...

get IP or Host name in Firefox extension
Hi Is it possible to get IP or Host name in Firefox extension? I need it to use for sending in SMTP EHLO command. Or maybe it's not necessary to send real IP/host? Thanks, telega > Is it possible to get IP or Host name in Firefox extension? Found it myself: nsIDNSService.myHostName ...

error unable to get host ip address
We are doing our first Sles 11 Oes 11 install in our tree. We have done all of the configuration steps we are at the Configure and start edirectory using "ndsconfig" step This fails with an Error Ndsconfig failed to configure and start Edirectory. under details it says unable to get host ip address. When we click okay, we just go around in a loop and can't get any farther. -- Pfleming ------------------------------------------------------------------------ Hello, do you have correctly configured the IP address of SLES11? If you put "ip a s...

Web resources about - Get host name from IP address - asp.net.getting-started

File:Ipv6 address.svg - Wikipedia, the free encyclopedia
I, the copyright holder of this work, release this work into the public domain . This applies worldwide. This file contains additional information, ...

Civil Defence continues to tackle blaze at The Address Downtown Dubai - The National
A lower part of the hotel building was still on fire at 8am Friday, a resident and a photographer from The National said.

Dubai fire at Address Downtown: Photographer’s narrow escape
A PHOTOGRAPHER has told of a harrowing 30 minutes he spent trapped on a ledge metres from the raging inferno that engulfed a skyscraper in Dubai ...

Dubai hotel fire: At least 16 injured as officials probe cause of blaze at The Address Downtown hotel ...
Investigators in Dubai are working to determine the cause of a fire that engulfed a 63-storey luxury hotel on New Year's Eve.

President Obama previews his final State of the Union address
The president is scheduled to deliver his final address next Tuesday to both chambers of Congress

Cameron pledges to address roots of UK Islamist extremism in 2016
... plan of social reform to be built on the country's recovering economic foundations. Prime Minister David Cameron pledged on Friday to address ...

Fire at downtown Dubai's highrise Address hotel
CNN Fire at downtown Dubai's highrise Address hotel CNN (CNN) A massive fire broke out Thursday night at the high-end Address hotel in downtown ...

'Grey's Anatomy' Stars Address Series' Future: 'This Show Is a Vampire, It Can't Be Killed'
'Grey's Anatomy' Stars Address Series' Future: 'This Show Is a Vampire, It Can't Be Killed'

Pathankot attack: Time for PM Modi to dump NRIs, address nation on language of India-Pak dialogue
I believe that for the Narendra Modi government, we NRIs have become a cop-out of the first order. We have been singularly responsible for having ...

Democrats unveil bills to address prison staffing shortages
The package includes bills that would give officers the ability to collectively bargain over workplace safety, require more on-the-job training ...

Resources last updated: 1/8/2016 11:05:23 AM