当前位置: 移动技术网 > IT编程>开发语言>c# > C#编程获取IP地址的方法示例

C#编程获取IP地址的方法示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#编程获取ip地址的方法。分享给大家供大家参考,具体如下:

1、获取客户端ip

/// <summary>
/// 获取客户端ip
/// </summary>
/// <returns></returns>
public string getclientip()
{
  string clientip = "";
  if (system.web.httpcontext.current != null)
  {
    clientip = system.web.httpcontext.current.request.servervariables["http_x_forwarded_for"];
    if (string.isnullorempty(clientip) || (clientip.tolower() == "unknown"))
    {
      clientip = system.web.httpcontext.current.request.servervariables["http_x_real_ip"];
      if (string.isnullorempty(clientip))
      {
        clientip = system.web.httpcontext.current.request.servervariables["remote_addr"];
      }
    }
    else
    {
      clientip = clientip.split(',')[0];
    }
  }
  return clientip;
}

2、服务器端获取客户端请求ip和客户端机器名称

/// <summary>
/// 服务器端获取客户端请求ip和客户端机器名称
/// </summary>
public static void getclientinfo()
{
  operationcontext context = operationcontext.current;
  messageproperties messageproperties = context.incomingmessageproperties;
  remoteendpointmessageproperty endpointproperty = messageproperties[remoteendpointmessageproperty.name] as remoteendpointmessageproperty;
  httprequestmessageproperty requestproperty = messageproperties[httprequestmessageproperty.name] as httprequestmessageproperty;
  string clientip = !string.isnullorempty(requestproperty.headers["x-real-ip"]) ? requestproperty.headers["x-real-ip"] : endpointproperty.address;
  string clientname = environment.machinename;
  console.writeline("clientip: " + clientip + "clientname:" + clientname);
}

ps:这里再为大家推荐几款ip相关工具供大家参考使用:

ip地址归属地在线查询工具:

在线ip地址/子网掩码计算与转换工具:

在线网络计算器|tcp/ip子网掩码计算与换算工具:

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#程序设计之线程使用技巧总结》、《winform控件用法总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网