DNS of the server where ASP.NET application is run - asp.net

How to get to know DNS name of the server where ASP.NET application is run?
I want to get string "www.somehost.com" if my application URL is http://www.somehost.com/somepath/application.aspx
Is there some property of Server, Contex, Session or Request objects for this?
Thanks!

This will get you the DNS IP for the server that is hosting the web site
void GetDNSServerAddress()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in nics)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPAddressCollection ips = ni.GetIPProperties().DnsAddresses;
foreach (System.Net.IPAddress ip in ips)
{
Console.Write(ip.ToString());
}
}
}
}
However, while writing this ive just seen your edited post, so i think this is what you are after is simply:
string host = Request.Url.Scheme + "://" + Request.Url.Host;
Hope this helps!

The HTTP_HOST server variable can give you what you need.
Request.ServerVariables("HTTP_HOST")

You can also get the 'machine name' using
System.Environment.MachineName

Related

Is there any way to get DNS Server upping or downing situation?

I am going to get DNS server situation (upping or downing) in asp.net and I could get server's IP address but I couldn't implement DNS server's situation!
Here is my code that get IP address.
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
if (dnsServers.Count > 0)
{
txtAdapterdescription.Text += adapter.Description;
foreach (IPAddress dns in dnsServers)
{
txtDNSserverbox.Text += dns.ToString();
}
}
}
Anyone can help me to implement DNS server's situation?
Thanks

Get LAN client machine name in servlet based web application

I have spring MVC application, that runs in LAN. In there client machines IP addresses are changing time to time. Therefore I want to get client machines names(Their machine name is fixed ),because I want to get client machine's details without creating log in.
Is that possible to get client machine's name?? if it's possible how??
Or is there any other way to get that user details
Edit:
codes I have tried so far
In HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String hostname = request.getRemoteUser(); //this gives null
String hostname = request.getRemoteHost(); //This gives host machine name
}
Edit: reply to #Eugeny Loy
In web.xml
<init-param>
<param-name>jcifs.smb.client.username</param-name>
<param-value>username</param-value>
</init-param>
In serverlet class
String username = config.getInitParameter("username");//This gives client IP address
I found the way to get client machine's name.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Logger.getLogger(this.getClass()).warning("Inside Confirm Servlet");
response.setContentType("text/html");
String hostname = request.getRemoteHost(); // hostname
System.out.println("hostname"+hostname);
String computerName = null;
String remoteAddress = request.getRemoteAddr();
System.out.println("remoteAddress: " + remoteAddress);
try {
InetAddress inetAddress = InetAddress.getByName(remoteAddress);
System.out.println("inetAddress: " + inetAddress);
computerName = inetAddress.getHostName();
System.out.println("computerName: " + computerName);
if (computerName.equalsIgnoreCase("localhost")) {
computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (UnknownHostException e) {
}
System.out.println("computerName: " + computerName);
}
Is that possible to get client machine's name??
You're probably referring to NetBIOS name here. If that's the case - you should use some library that implements NetBIOS/SMB/CIFS in java to do this.
if it's possible how??
Have a look on JCIFS. I won't give you the exact code snippet but this is the direction you should move to solve this.
Or is there any other way to get that user details
As far as I understand your problem, what you need is a way to identify host and you cannot rely on IP address for that.
If that's the case one of the other options would be using MAC address, but you'll probably wont be able to do this with pure java since this is more low-level protocol java normally deals with, so it will probably be less portable. This tutorial might help.
UPDATE
I come across NetBIOS/SMB/CIFS stack but I haven't worked with it in Java and JCIFS. That's why I won't give you specific code piece that will solve your issue but rather direction where you should look.
Check out NbtAddress class docs. Seems to be what you are looking for. Also check out the examples to get the idea how it can be used.

Detect which IP use in ASP.NET site with multiple bindings

I have an ASP.NET application setup in IIS 7 that uses two HTTP bindings on port 80, each with a different IP address.
This web server is behind a load balancer which could forward traffic on to the web server via either of the IP addresses (depending upon circumstances which aren't important).
Is there away for my application to detect which IP was being used by the load balancer - is it simply available via the REMOTE_ADDR server variable in the Request (assuming the load balancer overrides this)?
I think its an F5 load balancer is that helps!
In my case the answer was to use the LOCAL_ADDR variable as this represented the the server address on which the request came in - the load balancer.
Great info on server variables.
Cheers
This will display all of the relevant data: (from http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables(v=vs.90).aspx )
int loop1, loop2;
NameValueCollection coll;
// Load ServerVariable collection into NameValueCollection object.
coll=Request.ServerVariables;
// Get names of all keys into a string array.
String[] arr1 = coll.AllKeys;
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
Response.Write("Key: " + arr1[loop1] + "<br>");
String[] arr2=coll.GetValues(arr1[loop1]);
for (loop2 = 0; loop2 < arr2.Length; loop2++) {
Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
}
}
Within this you'll find REMOTE_ADDR which references the client, and SERVER_PORT which references the IIS host.

How to get the user IP address in Meteor server?

I would like to get the user IP address in my meteor application, on the server side, so that I can log the IP address with a bunch of things (for example: non-registered users subscribing to a mailing list, or just doing anything important).
I know that the IP address 'seen' by the server can be different than the real source address when there are reverse proxies involved. In such situations, X-Forwarded-For header should be parsed to get the real public IP address of the user. Note that parsing X-Forwarded-For should not be automatic (see http://www.openinfo.co.uk/apache/index.html for a discussion of potential security issues).
External reference: This question came up on the meteor-talk mailing list in august 2012 (no solution offered).
1 - Without a http request, in the functions you should be able to get the clientIP with:
clientIP = this.connection.clientAddress;
//EX: you declare a submitForm function with Meteor.methods and
//you call it from the client with Meteor.call().
//In submitForm function you will have access to the client address as above
2 - With a http request and using iron-router and its Router.map function:
In the action function of the targeted route use:
clientIp = this.request.connection.remoteAddress;
3 - using Meteor.onConnection function:
Meteor.onConnection(function(conn) {
console.log(conn.clientAddress);
});
Similar to the TimDog answer but works with newer versions of Meteor:
var Fiber = Npm.require('fibers');
__meteor_bootstrap__.app
.use(function(req, res, next) {
Fiber(function () {
console.info(req.connection.remoteAddress);
next();
}).run();
});
This needs to be in your top-level server code (not in Meteor.startup)
This answer https://stackoverflow.com/a/22657421/2845061 already does a good job on showing how to get the client IP address.
I just want to note that if your app is served behind proxy servers (usually happens), you will need to set the HTTP_FORWARDED_COUNT environment variable to the number of proxies you are using.
Ref: https://docs.meteor.com/api/connections.html#Meteor-onConnection
You could do this in your server code:
Meteor.userIPMap = [];
__meteor_bootstrap__.app.on("request", function(req, res) {
var uid = Meteor.userId();
if (!uid) uid = "anonymous";
if (!_.any(Meteor.userIPMap, function(m) { m.userid === uid; })) {
Meteor.userIPMap.push({userid: uid, ip: req.connection.remoteAddress });
}
});
You'll then have a Meteor.userIPMap with a map of userids to ip addresses (to accommodate the x-forwarded-for header, use this function inside the above).
Three notes: (1) this will fire whenever there is a request in your app, so I'm not sure what kind of performance hit this will cause; (2) the __meteor_bootstrap__ object is going away soon I think with a forthcoming revamped package system; and (3) the anonymous user needs better handling here..you'll need a way to attach an anonymous user to an IP by a unique, persistent constraint in their request object.
You have to hook into the server sessions and grab the ip of the current user:
Meteor.userIP = function(uid) {
var k, ret, s, ss, _ref, _ref1, _ref2, _ref3;
ret = {};
if (uid != null) {
_ref = Meteor.default_server.sessions;
for (k in _ref) {
ss = _ref[k];
if (ss.userId === uid) {
s = ss;
}
}
if (s) {
ret.forwardedFor = ( _ref1 = s.socket) != null ?
( _ref2 = _ref1.headers) != null ?
_ref2['x-forwarded-for'] : void 0 : void 0;
ret.remoteAddress = ( _ref3 = s.socket) != null ?
_ref3.remoteAddress : void 0;
}
}
return ret.forwardedFor ? ret.forwardedFor : ret.remoteAddress;
};
Of course you will need the current user to be logged in. If you need it for anonymous users as well follow this post I wrote.
P.S. I know it's an old thread but it lacked a full answer or had code that no longer works.
Here's a way that has worked for me to get a client's IP address from anywhere on the server, without using additional packages. Working in Meteor 0.7 and should work in earlier versions as well.
On the client, get the socket URL (unique) and send it to the server. You can view the socket URL in the web console (under Network in Chrome and Safari).
socket_url = Meteor.default_connection._stream.socket._transport.url
Meteor.call('clientIP', socket_url)
Then, on the server, use the client's socket URL to find their IP in Meteor.server.sessions.
sr = socket_url.split('/')
socket_path = "/"+sr[sr.length-4]+"/"+sr[sr.length-3]+"/"+sr[sr.length-2]+"/"+sr[sr.length-1]
_.each(_.values(Meteor.server.sessions), (session) ->
if session.socket.url == socket_path
user_ip = session.socket.remoteAddress
)
user_ip now contains the connected client's IP address.

add a host header to a website on IIS 7 programmatically

I want to add a host header to a website which is working on IIS7 through a web application (asp.net 4.0 / C#).There are some examples in internet,but i guess most of them dont work on iis7.
(note:the web application is being hosted in same server so i guess there wont be a security problem while changing iis configurations)
Any help is appreciated,thanks
I found this solution and it works for me.This is a little function with couple parameters,just you have to find the id of yourwebsite in your iss configuration.After that you have to give the ip adress of the server (iis),and port number,and hostname to the function and it will add a hostheader by using the parameters you entered.For example
AddHostHeader(2, "127.0.0.1:81", 81, "newsHostHeader");
static void AddHostHeader(int? websiteID, string ipAddress, int? port, string hostname)
{
using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID.ToString()))
{
var bindings = directoryEntry.Properties["ServerBindings"];
var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);
if (bindings.Contains(header))
throw new InvalidOperationException("Host Header already exists!");
bindings.Add(header);
directoryEntry.CommitChanges();
}
}
(note:do not forget to add to the page using
System.DirectoryServices; using Microsoft.Web.Administration; )
The above solution didn't quite work with IIS7.5 for me.
I eventually had to do this
http://www.iis.net/configreference/system.applicationhost/sites/site/bindings/binding

Resources