【问题标题】:VB.NET TCP Server/Client - Get IP of connected clientVB.NET TCP 服务器/客户端 - 获取连接客户端的 IP
【发布时间】:2018-12-30 00:50:53
【问题描述】:

我正在尝试获取已连接客户端的 IP 地址,但我不知道我做错了什么。我在哪里可以找到它?我想在Sub AcceptClient 附近。我试图将cClient 转换为字符串,但结果总是TrueFalse。我正在尝试从 cClient 获取参数 ar,这给了我一个空结果。
Client.Client.RemoteEndPoint 不起作用或我无法正确使用它。


来自服务器项目的 Form1.vb
Imports System.IO, System.Net, System.Net.Sockets

Public Class Form1
    Dim Listener As TcpListener
    Dim Client As TcpClient
    Dim ClientList As New List(Of ChatClient)
    Dim sReader As StreamReader
    Dim cClient As ChatClient

    Sub xLoad() Handles Me.Load
        Listener = New TcpListener(IPAddress.Any, 3818)
        Timer1.Start()
        Listener.Start()
        xUpdate("Server Started", False)
        Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''Set view property
        ListView1.View = View.Details
        ListView1.GridLines = True
        ListView1.FullRowSelect = True

        'Add column header
        ListView1.Columns.Add("Adres IP", 120)
        ListView1.Columns.Add("Nazwa użytkownika", 120)
    End Sub

    Sub AcceptClient(ByVal ar As IAsyncResult)
        cClient = New ChatClient(Listener.EndAcceptTcpClient(ar))
        AddHandler(cClient.MessageRecieved), AddressOf MessageRecieved

        AddHandler(cClient.ClientExited), AddressOf ClientExited
        ClientList.Add(cClient)
        xUpdate("New Client Joined", True)

        Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
    End Sub

    Sub MessageRecieved(ByVal Str As String)
        xUpdate(Str, True)
    End Sub

    Sub ClientExited(ByVal Client As ChatClient)
        ClientList.Remove(Client)
        xUpdate("Client Exited", True)
    End Sub

    Delegate Sub _xUpdate(ByVal Str As String, ByVal Relay As Boolean)
    Sub xUpdate(ByVal Str As String, ByVal Relay As Boolean)
        On Error Resume Next
        If InvokeRequired Then
            Invoke(New _xUpdate(AddressOf xUpdate), Str, Relay)
        Else
            Dim nStart As Integer
            Dim nLast As Integer

            If Str.Contains("</>") Then
                nStart = InStr(Str, "</></>") + 7
                nLast = InStr(Str, "<\><\>")
                Str = Mid(Str, nStart, nLast - nStart)

                'dzielenie strina po odpowiednim syymbolu na przed i po symbolu :D

                Dim mystr As String = Str
                Dim cut_at As String = ","
                Dim x As Integer = InStr(mystr, cut_at)

                Dim string_before As String = mystr.Substring(0, x - 1)
                Dim string_after As String = mystr.Substring(x + cut_at.Length - 1)

                Dim otherItems As String() = {string_after}
                ListView1.Items.Add(string_before).SubItems.AddRange(otherItems) 'use SubItems
            ElseIf Str.Contains("<A>") Then
                nStart = InStr(Str, "<A>") + 4
                nLast = InStr(Str, "<B>")
                Str = Mid(Str, nStart, nLast - nStart)

                ListBox2.Items.Add(Str & vbNewLine)
            Else
                TextBox1.AppendText(Str & vbNewLine)
                If Relay Then Send(Str & vbNewLine)
            End If
        End If
    End Sub

    Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
        If e.KeyCode = Keys.Enter Then
            e.SuppressKeyPress = True
            xUpdate("Server Says: " & TextBox2.Text, True)
            TextBox2.Clear()
        End If
    End Sub

    Sub Send(ByVal Str As String)
        For i As Integer = 0 To ClientList.Count - 1
            Try
                ClientList(i).Send(Str)
            Catch
                ClientList.RemoveAt(i)
            End Try
        Next
    End Sub
End Class


来自服务器项目的 ChatClient.vb
Imports System.Net.Sockets, System.IO

Public Class ChatClient
    Public Event MessageRecieved(ByVal Str As String)
    Public Event ClientExited(ByVal Client As ChatClient)
    Private sWriter As StreamWriter
    Public Client As TcpClient

    Sub New(ByVal xclient As TcpClient)
        Client = xclient
        client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
    End Sub

    Private Sub Read()
        Try
            Dim sr As New StreamReader(Client.GetStream)
            Dim msg As String = sr.ReadLine()
            RaiseEvent MessageRecieved(msg)
            Client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf Read), Nothing)
        Catch
            RaiseEvent ClientExited(Me)
        End Try
    End Sub

    Public Sub Send(ByVal Message As String)
        sWriter = New StreamWriter(Client.GetStream)
        sWriter.WriteLine(Message)
        sWriter.Flush()
    End Sub
End Class

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow!如果您发现我的回答解决了您的问题,请按我帖子左侧的勾号/复选标记将其标记为已接受。更多信息请参考:How does accepting an answer work?谢谢!
  • 由于您是新来的,我还建议您使用Tour(如果您还没有的话)。它将帮助您深入了解 Stack Overflow 的全部内容! :)

标签: vb.net ip client-server tcplistener


【解决方案1】:

您可以通过将Socket.RemoteEndPoint property 转换为IPEndPoint 来从底层套接字获取IP 地址:

Dim Address As IPAddress = CType(cClient.Client.Client.RemoteEndPoint, IPEndPoint).Address

MessageBox.Show(Address.ToString()) 'Example.

【讨论】:

  • 得到了和以前一样的错误:BC30456 "RemoteEndPoint" is not part of the Tcpclient
  • @Vantage92 :抱歉,没有看到 cClientChatClient。应该是cClient.Client.Client.RemoteEndPoint。我编辑了我的答案来解决这个问题。
  • 谢谢。那是有效的,但它向我显示了 127.0.0.1,这不是我的客户地址 ip。我们能改变什么?
  • @Vantage :您当前是否在同一台计算机上运行服务器和客户端?如果是这样,那实际上就是您客户的 IP。 127.0.0.1(也称为localhost)是本地计算机。一旦你开始在不同的计算机上使用它,IP 应该是不同的。
  • 没错,服务器和客户端在同一台电脑上运行。但如果人们从局域网加入,他们将拥有 127.0.0.1 或他们的局域网地址 ip?
猜你喜欢
  • 2012-08-31
  • 1970-01-01
  • 2021-08-12
  • 2017-08-04
  • 2020-12-17
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多