HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Best way to identify a computer in LAN C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lanidentifywaycomputerbest

Problem

I have a web application to manage computers. Every registered computer is locally querying the latest information and updates the database with it in a 10 minute cycle.

But the computer is only allowed to update its information and nothing else. Currently I'm identifying the computer like this:

I get its hostname from the "remote_addr" variable

string senderHostname = (Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName).Split('.')[0];


Then I compare the hostname of the sender computer with the hostname of the computer which should be updated.

if (senderHostname.Equals(targetHostname, StringComparison.InvariantCultureIgnoreCase)) {
 // allowed
}
else {
 // forbidden
}


If they are the same, then I'm allowing the update, otherwise not.

I know that this code is very very ugly and I would be interested in a best practice to do this.

All the code:

```
protected void Page_Load(object sender, EventArgs e)
{
try
{
clientMachineName = (Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName).Split('.')[0];
}
catch (Exception)
{
clientMachineName = "n/a";
}

if (!String.IsNullOrEmpty(Request.QueryString["status"]) && !String.IsNullOrEmpty(Request.QueryString["value"]))
{
String macAddress = Request.QueryString["status"];
String statusCode = Request.QueryString["value"];

if (clientMachineName.Equals(getHostName(macAddress), StringComparison.InvariantCultureIgnoreCase))
{
ComputerDbCommunicator communicator = new ComputerDbCommunicator();
communicator.insertIntoComputerDb("UPDATE [Computer] SET [statuscode] = " + statusCode + " WHERE [macaddress] = '" + macAddress + "'");

communicator.closeConnections();
communicator = null;

Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "text/plain");
Response.Write(statusCode);

Solution

You've got some duplication in there;

Perhaps you can create a function with a string argument that will handle response writing?

protected void CreateResponse(string response){
    Response.Clear();
    Response.ClearHeaders();
    Response.AddHeader("Content-Type", "text/plain");
    Response.Write(response);
    Response.Flush();
    Response.End();
}


To me that seems far more concerning than the way in which you retrieve the hostname.

Code Snippets

protected void CreateResponse(string response){
    Response.Clear();
    Response.ClearHeaders();
    Response.AddHeader("Content-Type", "text/plain");
    Response.Write(response);
    Response.Flush();
    Response.End();
}

Context

StackExchange Code Review Q#78624, answer score: 3

Revisions (0)

No revisions yet.