So I have a very basic script:
#region Get Hostname IP
IPAddress[] dnsRecords = Dns.GetHostAddresses(hostname);
string ipHostname = dnsRecords[0].ToString();
if (ipHostname.Length == 0) {
responseCode = imapLoginResponse.Failed;
return false;
}
#endregion
#region Try make a request to the Host, Port
try {
_Connection = new TcpClient(ipHostname, port);
} catch (SocketException ex) {
System.Diagnostics.Debug.Write("-" + hostname + "-" + ipHostname + "- " + ex.Message);
responseCode = ex.Message == "No such host is known" || ex.Message.StartsWith("No connection could be made because the target machine actively refused it") ? imapLoginResponse.BadHostname : imapLoginResponse.Failed;
return false;
}
The code above simply tries to connect to an IMAP Server.
Get imap.{domain.ext} DNS Record IP
Try connect to that IP with port 993
Voila
What's happening for either dead/bad/abandoned/parked websites is:
Get imap.{domain.ext} DNS Record IP, somehow will get one even though it doesn't exist
Try to connect to that IP with port 993
Server doesn't respond resulting in a timeout
Now what do I do? I cant turn this down to an "BadHostname" as it could just be a connection issue on the user's end or even not connected to internet.
If I were to just retry here, it will end up infinitely looping.
While yes, I could do a 5 retries == invalid thing, but that's not accurate and could still be a temporary internet issue.
My question is, why is it getting a DNS Record IP for a record that doesnt exist?
And what am I meant to do when something like this occurs?
If you need to test, try it with this: imap.celerityinc.com (no celebrityinc.com) and you can see for yourself.
Name resolution and services provided on an IP address are independent.
You get a DNS record because it does exist at some point in the DNS hierarchy with a certain lifetime.
What you can do when something like this occurs? Flush your local DNS cache. Try different DNS servers. Go back to the SOA with your own DNS query solution.
Related
I am trying to log the client IP address for one of the applications that I have build. It works OK on the dev server. But as soon as we deploy the solution on to the production server, which has load balancer,it seems to log the Load Balancer's IP address rather than the client IP.
I understand that we need to add HTTP_X_FORWARD_FOR header.
This is my code :
private static string GetCurrentIp()
{
String clientIP =
(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null) ?
HttpContext.Current.Request.UserHostAddress :
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
return clientIP;
}
Appreciate if someone could help me identify the mistake that I have done
Sometimes your visitors are behind either a proxy server or a router and the standard Request.UserHostAddress only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
above code helps you to make it working.
Another viable option is:
var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;
Not saying you've got to use this, but the process is much simpler for you with this method.
Previously this was broken in .NET Core RC1 but turns out it's production ready since RC2.
as you can see I am using below code to get any real ip address on any PC connected to the internet but I was wondering if there is way to get the real IP address without calling a site to get it ?
and if there is a way to send it to my hotmail/gmail/...etc account as email
i found many ways on the internet but all of them are blocked by mail servers
private string getExternalIp()
{
try
{
string externalIP;
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
catch
{
MessageBox.Show("Please Call Technical Support", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
I don't think there is any reliable method to get external IP address without actually connecting to something. This is because your machine may be behind NAT and simply doesn't have information what is it's external IP address.
Of course if you know this machine has configured it's external IP address on one of it's interfaces, you may list all interfaces using NetworkInterface.GetAllNetworkInterfaces.
I am able to ping smtp.mail.yahoo.com from my system but when i send email from following code using yahoo address it gives error transport failed to connect to server.
The same code successfully sends the email from gmail account.
I am using port 465 for yahoo.
MailMessage oMsg = new MailMessage();
oMsg.From = from.Text;
oMsg.To = to.Text;
oMsg.Subject = "Hi";
oMsg.BodyFormat = MailFormat.Html;
oMsg.Body = msg.Text;
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", port);
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", host);
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);
WebProxy proxy = WebProxy.GetDefaultProxy();
if (proxy.Address != null)
{
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/urlproxyserver", proxy.Address.Host);
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/proxyserverport", proxy.Address.Port);
}
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",from.Text);
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pass.Text);
// ADD AN ATTACHMENT.
/* MailAttachment oAttch = new MailAttachment(path+ "\\Image.bmp", MailEncoding.Base64);
oMsg.Attachments.Add(oAttch);*/
SmtpMail.SmtpServer.Insert(0,host);
if (proxy.Address != null)
MessageBox.Show("Sending via proxy settings: " + proxy.Address.ToString());
try
{
SmtpMail.Send(oMsg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
oMsg = null;
Any ideas why this error occurs?
Being able (or not) to ping a host does not say anything about whether you will be able to connect to a particular service on it. For that, you need to try to actually establish a connection. (And of course, the fact that you can establish a connection does not necessarily imply that the service in question is working properly.)
Usually, it's a good idea to use telnet to try connecting to the remote host on the port in question. The syntax on the command line is simply telnet host.fqdn.example.com portnumber. This will tell you if there is anything at all at the other end of the pipe responding to connection attempts, which is a first step in determining where the problem is.
Second, it's usually a good idea to trim the code to the minimal version that exhibits the problematic behavior, and include the full code to show the problematic behavior. You are using a number of variables in your code which we really know nothing about.
Some ISPs block outgoing connections to the SMTP ports on hosts other than their own mail servers, to reduce the amount of outgoing spam. Maybe there is a typo in the value in host? Maybe you are inadvertantly using some unexpected MailMessage implementation? And so on.
That said, I would definitely first try to connect to the mail server in question manually, through a proxy if you are using one to connect using that code. If that doesn't work either, then your problem at least has nothing to do with the code in the question, and you can look elsewhere (in which case one possible candidate would be ISP filters; maybe they have a list of allowed external SMTP hosts and Yahoo's isn't on it?).
how can I get the client's computer name in a web application. The user in a network.
Regards
// Already tryed this option
string IP = System.Web.HttpContext.Current.Request.UserHostAddress;
string compName = DetermineCompName(IP);
System.Net.IPHostEntry teste = System.Net.Dns.GetHostEntry(IP);
ssresult = IP + " - " + teste.HostName;
// TODO: Write implementation for action
private static string DetermineCompName(string IP)
{
IPAddress myIP = IPAddress.Parse(IP);
IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);
string[] compName = GetIPHost.HostName.ToString().Split('.');
return compName[0];
}
All of that, gives me only the IP :/
You can't do this in a way that is guaranteed to work.
The closest you will be able to get is to go down the route of doing a reverse dns lookup using System.Net.Dns.GetHostEntry which is what you have already tried.
The problem is that your machine has no way of knowing the hostname of a remote web client via its IP address alone (unless it is on the same subnet, in which case you may be able to retrieve it).
You have to fall back on your DNS infrastructure being able to map the IP back into a hostname [this is what nslookup does when you type in a hostname], and plenty of places just won't bother setting up reverse IP records.
Plus, often if they do, they won't match the hostname. It is quite common to see a reverse lookup for "1.2.3.4" come back as something line "machine-1.2.3.4", instead of the actual hostname.
This problem is exacerbated further if the clients are behind any sort of Network Address Translation so that many client computers have a single IP from an external perspective. This is probably not the case for you since you state "The user in a network".
As an aside, if you go to the server and type in, at a command prompt,
nslookup <some ip>
(where is an example of one of these client machines), do you get a hostname back?
If you do, then System.Net.Dns.GetHostEntry should be able to as well, if not then it probably can't for the reasons mentioned above.
you can get the windows machine name with - System.Environment.MachineName
Assuming your clients are Windows based running IE you could use this client side code to get the names and pass them back to the server:
<script type="text/javascript">
function create()
{
var net = new ActiveXObject("wscript.network");
document.write(net.ComputerName);
}
</script>
Yeah would require you to keep requesting and caching the computers terribly inefficient, was a bad idea.
I would go with running nslookup in the background I haven't tested this code and neither is it handling errors for failures, but basically, you can do:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo sInfo = new System.Diagnostics.ProcessStartInfo("nslookup.exe", "192.168.1.100");
string result = process.StandardOutput.ReadToEnd();
Then just parse the result value.
Try as I might, I'm unable to resolve an address to IP. The code snippet is shown below. I keep getting the No such host is known exception, even though I could access google with my browser (The DNS server is almost certainly working). I'm however behind company's firewall.
try
{
foreach (IPAddress address in Dns.GetHostAddresses("www.google.com"))
{
Console.WriteLine(address.ToString());
}
}
catch (SocketException e)
{
Console.WriteLine("Source : " + e.Source); // System
Console.WriteLine("Message : " + e.Message); // No such host is known
}
There is nothing wrong with your code. Given that you can access www.google.com from a web browser the next most likely problem is that the web browser is using a proxy server. The web browser is actually accessing www.google.com through the proxy server which is allowed through the firewall. The simple application you wrote is not allowed through the firewall and is resulting in an exception.
You can verify this by looking at the proxy settings in Internet Explorer.
Tools -> Options -> Connections -> Lan Settings
There will be a proxy server group of settings. If there is a value present, this is almost certainly your problem.
You need to set up the proxy:
here's a snippet that should set it up for all the following calls:
protected void SetupProxy(string proxyUrl, string proxyLogin, string proxyPassword, string[] proxyBypass)
{
WebProxy proxy = new WebProxy(proxyUrl);
proxy.Credentials = new NetworkCredential(proxyLogin, proxyPassword);
proxy.BypassList = proxyBypass;
proxy.BypassProxyOnLocal = true;
WebRequest.DefaultWebProxy = proxy;
}
Rather than try through a browser, try pinging www.google.com (or some other host, of course) from the command line.
The ping itself may well not work, but it should show the IP address resolution first. If you get an error message like this:
Ping request could not find host www.google.com.
Please check the name and try again.
then it's likely that the proxy server is doing the DNS lookup for you when you're browsing, and your DNS server is either not working or your machine's network settings are incorrect.