LoginSignup
5
11

More than 5 years have passed since last update.

ASP.netでIPアドレスを取得する

Posted at

C# IISを使ったASP.netで、クライアントのIPアドレスを取得する

        // 要求元クライアントのIPアドレス
        string userIp = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        // または以下(こっちの方が文字列リテラルが含まれないので美しい)
        userIp = System.Web.HttpContext.Current.Request.UserHostAddress;

なお、実行環境自身のIPアドレスを取るには

        IPAddress[] lIp = Dns.GetHostAddresses(Dns.GetHostName());

        // IPv4を抽出する必要がある
        foreach (var iIp in lIp)
        {
            if (iIp.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                return iIp.ToString();
            }
        }
5
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
11