Right now i have the requirement to find some PC's Hostname by his IP Address and i solved this problem with this function:
/// <summary>
/// Returns the DNS Name of IP Address without the Domain.
/// </summary>
public string GetDNSNameFromReverseLookUp(string ip)
{
IPAddress hostIPAddress = IPAddress.Parse(ip);
IPHostEntry hostInfo = Dns.GetHostEntry(hostIPAddress);
return hostInfo.HostName.Substring(0, hostInfo.HostName.IndexOf('.'));
}
But i'm not happy with this substring() solution of the problem.
Is it allowed to use this function this way? Or do i have to fear some network issues in the future? Are there better (more secure) ways to get to the hostname without domain?
I'm looking for an more network secure solution, not another way to handle strings. As mentioned in the comments I fear a little bit, that not every OS returns the Hostname in the format:[Hostname].[Domainname].
You will get an error if pc are not joined to a domain. Since the (dot) is not found, and so the use of split function is the most reasonable. I've already checked.
Try this
public string GetDNSNameFromReverseLookUp(string ip)
{
IPAddress hostIPAddress = IPAddress.Parse(ip);
IPHostEntry hostInfo = Dns.GetHostEntry(hostIPAddress);
return hostInfo.HostName.Split('.')[0];
}
Related
I wrote a Windows Service which monitors devices on our LAN by (among other things) pinging them (using Ping.Send(); .NET 4.6.1). For a small number of PCs (3), I "occasionally" (once/day?) will get a PingException from Send(<ipaddr>, 5000), with InnerException.Message == "No such host is known". The next time the Send() is executed (~60 seconds later), it succeeds. I am using an IP address, as opposed to a name, so it's not a DNS issue.
I talked to the network admins about this issue, but they don't believe anything is wrong with the physical hardware. What other problems could this error be indicating?
Ping.Send() has various parameters which includes a parameter type of string than can either be a valid IP address or valid host-name. I suspect that your using one of the string parameters and sometimes passing an invalid IP (extra space, invalid IP etc...) and the Send() method conditionally resolves that you must be passing a host-name hence the exception regarding DNS.
Rather than send a string, why not utilize the parameter of type IPAddress as you've already stated that it should always be an IP. You can do this by attempting to parse the string into an IPAddress as shown below:
if (IPAddress.TryParse("**IP String**", out var ip))
{
using (var pong = new Ping())
{
pong.Send(ip);
//Etc...
}
}
Note that you will still need to fix your invalid data whichever way you look at it.
We're trying to obtain all ip addresses and hostnames of machines on local network, we have a display box(BrightSign box) which is connected to local network and we want to have all information about that box. We can find ip address of it, but cannot get host name. So we can't determine which ip adresses is assigned to that box. (We can learn the ip address of the box by using its own program; but we want to detect automatically)
here the code we use in c#
`
public void scan(string subnet)
{
Ping myping;
PingReply reply;
IPAddress addr;
IPHostEntry host;
for (int i = 1; i < 255; i++)
{
string subnetn = "." + i.ToString();
myping = new Ping();
//string data = "aa";
//byte[] buffer = Encoding.ASCII.GetBytes(data);
//PingOptions optionss = new PingOptions(64, true);
int timeout = 1000;
reply = myping.Send(subnet + subnetn);
if (reply.Status == IPStatus.Success)
{
try {
addr = IPAddress.Parse(subnet+subnetn);
host = Dns.GetHostEntry(addr);
txtHosts.AppendText(subnet + subnetn + host.HostName.ToString()+"\n");
}
catch {
}
}
}
}`
if we use this code, system can detect all ip but not host names belongs to telephone and the box i mentioned.
Briefly, we need to have all machine name and ip addresses on local network.
So, do you guys have any idea what's the problem and what can we do to solve this issue. We made some research and tried some ways. We tried to send ping the ip address which we cannot take the hostname and we realized that if ttl of machine is set to 64, we cannot take the hostname, but if its ttl is 128, we can manage to learn the hostname, i also adjusted ping settings to test this challenge, but i still have problem.
I am looking forward to hearing your response.
Thank you all.
Machine name could be DNS or NETBIOS or something else. I recommend you check out NMAP and see what it can do. If you want to emulate that, you can ask about a specific requirement. For example, getting a DNS name means querying the DNS server, a computer wont reply with a name just from an ICMP ping. If the computer security settings allow it, you can do a netbios query, or use WMI, or if you are in a domain, query the domain server.
I don't know what brightsign is, but there is no law that says a device must have a DNS name, some appliances just use IP address and thats it. Also there's no law that says a device must respond to ping or any other protocol.
I've got this so far...
public static HttpListener listener = new HttpListener();
public static string startUpPath = Application.StartupPath;
public WebServer()
{
listener.Start();
listener.Prefixes.Add("http://(here I want my public ip)/");
Thread t = new Thread(new ThreadStart(clientListener));
t.Start();
}
But when I initialize the class it says "The specified Network format is not valid"
The translation may not be perfect because my visual studio language is in Spanish.
My ip looks like 95.^^.^^^.^^ and I think that may be the problem because it works when I use my local ip.
//Edited
The exact exception is:
"El formato del nombre de red especificado no es vĂ¡lido"
Which is"The specified network name is not valid".
If I add the prefix
"http:// + :80/"
it still going, but how can I access that through my public ip?
When setting this up you should use your internal IP, since that is the actual IP you are listening on.
In-order to get traffic from the your external IP, you need to forward that traffic from your router to your computer that is listening on its internal IP.
One way to set it up is to use port forwarding, from your router, you would want to direct any traffic that comes in on port 80 to your computer.
More info:
http://en.wikipedia.org/wiki/Port_forwarding
As Jamie said, your HTTPListener should be bound to the IP address on the network card where the application is running. Unless you have a NIC that is actually configured with a public IP (e.g. not going through a router) then your private address is the one to use.
An easy way to check this is to run IPCONFIG and see what IP address is listed.
Using C# Winforms I am trying to automatically detect the local machines IP address through which it can connect to a particular remote DNS/IP address.
One senario is running over a VPN, with the remote address being 10.8.0.1 and local address being 10.8.0.6, netmask of 255.255.255.252
Iterating through the local addresses and checking if the remote and local are on the same subnet obviously fails and I am unsure of how else to do this.
Here is some sample code that should get you the information you're looking for. It creates a UDP socket and calls Connect() on it (effectively a NOOP), and then checks the local address.
static EndPoint GetLocalEndPointFor(IPAddress remote)
{
using (Socket s = new Socket(remote.AddressFamily,
SocketType.Dgram,
ProtocolType.IP))
{
// Just picked a random port, you could make this application
// specific if you want, but I don't think it really matters
s.Connect(new IPEndPoint(remote, 35353));
return s.LocalEndPoint;
}
}
static void Main(string[] args)
{
IPAddress remoteAddress = IPAddress.Parse("10.8.0.1");
IPEndPoint localEndPoint = GetLocalEndPointFor(remoteAddress) as IPEndPoint;
if (localEndPoint == null)
Console.WriteLine("Couldn't find local address");
else
Console.WriteLine(localEndPoint.Address);
Console.ReadKey();
}
Note that this is effectively an implementation of this answer, but in C#.
The routing table determines which local port to use. I don't know of a way from C# to get it other than to run the route print CLI command. If there is a network match it uses that port, otherwise it uses the default route.
http://www.csharp-examples.net/local-ip/
Give that a shot.
string myHost = System.Net.Dns.GetHostName();
string myIP =
System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
MessageBox.Show(myIP);
TextReader read = new StreamReader(//Text file with network address);
var ip = read.ReadLine();
read.Close();
if (ip == //Need help with this part)
MessageBox.Show("You are on the network");
else
MessageBox.Show("You are not on the network");
I can get my computers address but I need to compare it to a network address and if it falls under that network address to show that it is.
If your program crashes when your IP is invalid, you can change it over to a try catch that checks for that exception (run it and crash it to find the exception). This is how I validated the IP in my multiplayer with Lidgren.
Though this is probably not the best way, it works.
One simple way to see if an ip is in a range is to convert the ip and the start and end of the range to longs (a function can be written for the conversion to a long from an IP address). Then see if the ip is between the two numbers.
For example:
IP to check: 172.17.1.25 -- Converted to long --> 172017001025
Range:
Start - 172.0.0.0 -- Converted to long --> 172000000000
End - 172.255.255.255 -- Converted to long --> 172255255255
Now just check if the ip is between the start and end values.
I recommend the IPNetwork utility that can be found on codeplex. It is pretty flexible and powerful. It will allow you to do a lot of things, and determining the network for a given ip address is one of them.
http://ipnetwork.codeplex.com/
The code should look like :
var ipnetwork = IPNetwork.Parse(ip);
if (ipnetwork.Contains(myIp)) {
// do some work...