如何在c#中获取tcp客户端ip和端口并显示?

时间:2018-01-22 12:47:55

标签: c# sockets tcp serversocket

我想得到tcp客户端的IP地址和端口,但是我不能这样做。我想在我的代码中使用套接字,除了tcp监听器类,我的目标是获取没有此类的客户端IP和端口。下面是我的代码:(我想在if(rc){}条件之前获取客户端IP地址和端口)

 namespace Example
{
public partial class TCP_Server : Form
{
    Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    Socket socketClient = null;
    public TCP_Server()
    {
        InitializeComponent();
        CheckForIllegalCrossThreadCalls = false;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public void start()
    {

        IPEndPoint ipens = new IPEndPoint(IPAddress.Parse(txt_ip.Text), int.Parse(txt_port.Text));
        socketServer.Bind(ipens);
        MessageBox.Show("wait");
        while (true)
        {
            socketServer.Listen(2);
            socketClient = socketServer.Accept();

            MessageBox.Show("accept");
            Thread trgetmsg = new Thread(new ThreadStart(getmsg));
            trgetmsg.Start();
        }
    }

    public void getmsg()
    {
        int counter = 0;
        string[] barray2 = new string[10];
        try
        {
            while (true)
            {
                byte[] barray = new byte[1024];
                EndPoint iprec = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4040);
                int rc = socketClient.ReceiveFrom(barray , ref iprec);
                barray2[counter] = Encoding.Unicode.GetString(barray, 0, rc);
                counter =counter+1;

                if (rc > 0)
                {
                     MessageBox.Show(iprec.);
                    if (barray2[0] == barray2[1])
                    {
                        listBox1.Items.Add("client: " + Encoding.Unicode.GetString(barray, 0, rc));
                        socketClient.Send(Encoding.Unicode.GetBytes(barray2[0])); 
                    }

                }

            }

        }
        catch { ;}


    }

1 个答案:

答案 0 :(得分:0)

这将提供已接受客户端的端点信息;

socketClient = socketServer.Accept();
var endPoint = (IPEndPoint)socketClient.RemoteEndPoint;