• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#里获取客户端IP,端口号的简单示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;//为了IPEndPoint而添加的引用
using System.Net.Sockets;

namespace GetClntIP
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener tcpListener = new TcpListener(9000);//监听的端口号,可根据需要修改
            tcpListener.Start();

            //loop for listen
            while (true)
            {
                Socket sock = tcpListener.AcceptSocket();

                //服务器当前时间
                DateTime connTime = DateTime.Now;
                Console.WriteLine("The time is :"+connTime.ToString());

                System.Net.IPAddress ipAdd;
                int port;

                //获得连接当前用户的IP以及端口号
                ipAdd = (sock.RemoteEndPoint as IPEndPoint).Address;
                port = (sock.RemoteEndPoint as IPEndPoint).Port;

                Console.WriteLine("The client IP :"+ipAdd.ToString ());
                Console.WriteLine("The client port :" + port.ToString());
            }

            tcpListener.Stop();
        }
    }
}

 

[附]获取本地IP:

//获得本地局域网IP地址

IPAddress [] AddressList=Dns.GetHostByName(Dns.GetHostName()).AddressList;

if(AddressList.Length<1)

{

       retern "";

}

retern AddressList[0].ToString();//注意这里数组参数为0

 

//获得拨号动态分配IP地址

IPAdress [] AddressList=Dns.GetHostByName(Dns.GetHostName()).AddressList;

if(AddressList.Length<2)

{

        return "";

}

return AddressList[1].ToString();//注意这里数组参数为1


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap