How to get the HostName, Ip of the machine hosting the asp.net application
How can i get the LocalhostName, Ip of the machine hosting the Application. For development it would be localhost
for deployment something different. This i need to initialize the SmtpClient to send emails through application
SmtpClient emailClient = new SmtpClient("host","port");//port is optional
i am looking for a permanent solution, no workarounds and no sniffing from response, request and this could be spoofed[hope i am not开发者_Go百科 crazy because no one can spoof the servers data in headers can they?]
If you want to configure SmtpClient class, you should have a look at the system.net > mailsettings entry of the web.config : http://msdn.microsoft.com/en-us/library/w355a94k.aspx
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>
And instanciate the StmpClient with parameterless constructor
var client = new SmtpClient();
if you use
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
and
public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
it should return something like
IsLocalIpAddress("localhost"); // true (loopback name)
IsLocalIpAddress("127.0.0.1"); // true (loopback IP)
IsLocalIpAddress("MyNotebook"); // true (my computer name)
IsLocalIpAddress("192.168.0.1"); // true (my IP)
IsLocalIpAddress("NonExistingName"); // false (non existing computer name)
IsLocalIpAddress("99.0.0.1"); // false (non existing IP in my net)
this can be simply modified to return the address you need
精彩评论