duheng
2024-05-22 f0aaa59c3bb1ef75affcacadbcc8fae21149f52c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
 
namespace IStation
{
    public static class TcpHelper
    {
        private const string _separator = ":";//IP与Port的分隔符
 
        /// <summary>
        /// 获取远程连接的IP地址
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <returns></returns>
        public static string GetRemoteIP(this TcpClient tcpClient)
        {
            return tcpClient.GetRemoteIPAndPort().IP;
        }
 
        /// <summary>
        /// 获取远程连接的Port
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <returns></returns>
        public static int GetRemotePort(this TcpClient tcpClient)
        {
            return tcpClient.GetRemoteIPAndPort().Port;
        }
 
        /// <summary>
        /// 获取IP和Port
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <returns></returns>
        public static TcpIPAndPort GetRemoteIPAndPort(this TcpClient tcpClient)
        {
            var ipAndPort = tcpClient.Client.RemoteEndPoint.ToString();
            var arr = ipAndPort.Split(new string[] { _separator }, StringSplitOptions.RemoveEmptyEntries);
            return new TcpIPAndPort(arr[0],Convert.ToInt32(arr[1]));
        }
 
 
 
 
 
    }
}