1

Hey evryone I am trying to create an IP adress comparison so when the user logs in he/she needs to be tested to see if the IP on mysql database is ip on system's computer

I keep getting error object reference not set to an object, because I do not know how to get users IP from C# i've tried many codes but cannot seem to convert them into int32s

here is my code

private void CheckIf1Login()
{
   MySqlConnection conn = new MySqlConnection(myConnection);
        MySqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = "SELECT ip_addr FROM `as_users` WHERE username = '" + Form1.TextBoxText + "'";
        conn.Open();
        MySqlCommand SelectCommand = new MySqlCommand("SELECT ip_addr'", conn);
        int IP2 = Convert.ToInt32(cmd.ExecuteScalar());
        string ipAddress = HttpContext.Current.Request.UserHostAddress;
        uint IP3 = GetIpAsUInt32(ipAddress);
        MessageBox.Show("" + IP3);
        if (IP2 == IP3)
       {
            MessageBox.Show("Whoops! It seems that your package subscribtion has expired, to renew it please click here.");
        }
        else
        {
            CheckPackageType();
        }
}

public uint GetIpAsUInt32(string ipString)
{
    IPAddress address = IPAddress.Parse(ipString);

    byte[] ipBytes = address.GetAddressBytes();

    Array.Reverse(ipBytes);

    return BitConverter.ToUInt32(ipBytes, 0);
}
Ghandour
  • 45
  • 1
  • 11
  • 1
    what's the value of "ipString"? Please debug and tell us at which statement an exception is thrown out. –  Jan 24 '14 at 01:34
  • the string is what it says you input it such as ("127.0.0.1) in this case I chose to use string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];//this is whats failing I believe. – Ghandour Jan 24 '14 at 01:37
  • If this is ASP.Net you should use HttpContext.Current#Request#UserHostAddress instead – Machinarius Jan 24 '14 at 01:38
  • yes this is asp.net, tried changing this string ipAddress = HttpContext.Current.Request.UserHostAddress; didn't work guessing now it might be my int converter? – Ghandour Jan 24 '14 at 01:40
  • I updated the code with changes I made – Ghandour Jan 24 '14 at 01:47

1 Answers1

1

This answer suggests that you may be going about this the wrong way. Have you tried using HttpRequest.UserHostAddress?

Community
  • 1
  • 1
theMayer
  • 15,456
  • 7
  • 58
  • 90