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

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Net;//为了IPEndPoint而添加的引用
 5 using System.Net.Sockets;
 6 
 7 namespace GetClntIP
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             TcpListener tcpListener = new TcpListener(9000);//监听的端口号,可根据需要修改
14             tcpListener.Start();
15 
16             //loop for listen
17             while (true)
18             {
19                 Socket sock = tcpListener.AcceptSocket();
20 
21                 //服务器当前时间
22                 DateTime connTime = DateTime.Now;
23                 Console.WriteLine("The time is :"+connTime.ToString());
24 
25                 System.Net.IPAddress ipAdd;
26                 int port;
27 
28                 //获得连接当前用户的IP以及端口号
29                 ipAdd = (sock.RemoteEndPoint as IPEndPoint).Address;
30                 port = (sock.RemoteEndPoint as IPEndPoint).Port;
31 
32                 Console.WriteLine("The client IP :"+ipAdd.ToString ());
33                 Console.WriteLine("The client port :" + port.ToString());
34             }
35 
36             tcpListener.Stop();
37         }
38     }
39 }

 

 

[附]获取本地IP:

 1 //获得本地局域网IP地址
 2 
 3 IPAddress [] AddressList=Dns.GetHostByName(Dns.GetHostName()).AddressList;
 4 
 5 if(AddressList.Length<1)
 6 
 7 {
 8 
 9        retern "";
10 
11 }
12 
13 retern AddressList[0].ToString();//注意这里数组参数为0
14 
15  

 

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

 1 IPAdress [] AddressList=Dns.GetHostByName(Dns.GetHostName()).AddressList;
 2 
 3 if(AddressList.Length<2)
 4 
 5 {
 6 
 7         return "";
 8 
 9 }
10 
11 return AddressList[1].ToString();//注意这里数组参数为1

 

posted @ 2018-03-12 10:54  中创IT空间  阅读(868)  评论(0编辑  收藏  举报