6
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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();
            }
        }
6
12
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
6
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?