Bot
Bot

Reputation: 45

How to get clients computer name using asp.net mvc?

I am supporting a system that needs to get the client's computer name I try different codes but all of them just get the computer name of the host server, not the client's computer name. Here's the snippet:

 public void CreateEvents(string className, string eventName, string eventData, string userId)
    {
        string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
        string compname= HttpContext.Current.Request.UserHostAddress;
       

        var browser = HttpContext.Current.Request.Browser.Browser + " " + HttpContext.Current.Request.Browser.Version;

        if (string.IsNullOrEmpty(userId))
        {
            userId = compname;
        }

        var entity = new EventLog
        {
            ClassName = className,
            EventName = eventName,
            EventData = eventData,
            IpAddress = ipAddress,
            Browser = browser,
            UserId = userId,
            CreatedDate = DateTime.Now
        };

        _db.EventLogs.Add(entity);
        _db.SaveChanges();
    }

    public string GetIpAddress()
    {
       HttpContext context = System.Web.HttpContext.Current;
        string compname=    context.Request.UserHostAddress; //System.Net.Dns.GetHostName();
        return compname;
    }

Upvotes: 4

Views: 13382

Answers (3)

Amir  Ashurov
Amir Ashurov

Reputation: 21

you can use

HttpContext.Request.UserHostAddress 

for getting the IP address, also Request has UserHostName but I am not sure about this property

Upvotes: 2

EdSF
EdSF

Reputation: 12341

No you can't, unless the client sends such info when making HTTP requests. By "client", I'm referring to any - some app, browser, etc.

You can inspect your own browser request flow using standard browser dev tools and see exactly what info your browser is sending. It will not have your machine name (unless something in your machine is and that would likely be a problem).

That said, HTTP Header data is what you have aside from standard network info such as IP address (which also isn't guaranteed to be the client's IP address - it could be the client's network address). The closest you can get to is hostname if it exists, and even then, just like IP address, is not guaranteed to be machine name.

A possible exception would be in an internal network (LAN).

Upvotes: 6

slon
slon

Reputation: 1030

You can get computer name as follows:

Environment.MachineName.ToString()

You can get hosting server name as follows:

Server.MachineName.ToString()

Upvotes: -2

Related Questions