[导入]【原】C#里获取客户端IP,端口号的简单示例

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


文章来源: http://meymz.blog.163.com/blog/static/381209212007711021129

转载于:https://www.cnblogs.com/raindust/archive/2007/08/13/854242.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值