0

I'm trying to get the IP address of the connected client but I don't know what I doing wrong. Where I can find it? I think near Sub AcceptClient. I was trying to convert cClient to string, but it always results to True or False. I'm trying to get the argument ar from cClient, which gives me an empty result.
Client.Client.RemoteEndPoint doesn't work or I can't use it correctly.


Form1.vb from Server project
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 from Server project
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
Amit Verma
  • 8,660
  • 8
  • 35
  • 40
Vantage92
  • 3
  • 1
  • 3
  • Since you're new here I also recommend you take the [Tour](https://stackoverflow.com/tour) (if you haven't already). It'll help you get an insight in what Stack Overflow is all about! :) – Visual Vincent Jul 22 '18 at 10:29

1 Answers1

1

You can get the IP address from the underlying socket by converting the Socket.RemoteEndPoint property into an IPEndPoint:

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

MessageBox.Show(Address.ToString()) 'Example.
Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
  • Got same error like I had before: BC30456 "RemoteEndPoint" is not part of the Tcpclient – Vantage92 Jul 22 '18 at 10:32
  • 1
    @Vantage92 : Sorry, didn't see that `cClient` was a `ChatClient`. It should be `cClient.Client.Client.RemoteEndPoint`. I edited my answer to fix that. – Visual Vincent Jul 22 '18 at 10:35
  • Thanks. That is working but it show me 127.0.0.1 and that isn't my client adres ip. What can We change? – Vantage92 Jul 22 '18 at 10:43
  • @Vantage : Are you currently running the server and client on the same computer? If so, that infact is your client's IP. `127.0.0.1` (also referred to as `localhost`) is the local computer. The IP should be different once you start using this across different computers. – Visual Vincent Jul 22 '18 at 10:45
  • It's true, running server and client on the same computer. But if people will join from the Lan network they will have 127.0.0.1 or thier lan adress ip? – Vantage92 Jul 22 '18 at 10:48
  • @Vantage92 : They will see each others' LAN IP. `127.0.0.1` **is only** displayed if **both** the server and its _connected_ client runs on the same computer. – Visual Vincent Jul 22 '18 at 10:50
  • That is great and working! Tested on another computer in lan. Thank You very much Visual Vincent! – Vantage92 Jul 22 '18 at 10:58
  • @Vantage92 : No problem, glad I could help! Good luck with your program! :) – Visual Vincent Jul 22 '18 at 11:00
  • Can You tell me how input this ip adress into a ListView? I put it to "AcceptClient" Sub but, ListView1.Items.Add(Address.ToString()) but debuger says: System.InvalidOperationException: "Invalid operation between threads: Access to the" ListView1 "control is accessed from a thread other than the thread in which it was created." I should invoke? But how to do it? Thanks – Vantage92 Jul 22 '18 at 14:23
  • @Vantage92 : The following answer of mine will help you with that, be sure to read everything from _**Accessing the UI thread**_ and down: https://stackoverflow.com/a/45571728/3740093 – Visual Vincent Jul 22 '18 at 15:31
  • Got it! Thanks again! – Vantage92 Jul 22 '18 at 16:35
  • Vincent, Got another question to You - How to get ip address of disconnected client? If I use same code in sub "ClientExited" that show me ip address of last connected client. – Vantage92 Aug 01 '18 at 07:01
  • @Vantage92 : When a client has disconnected/crashed the underlying socket of the endpoint would be closed, so I don't think you can unless you cache it after establishing a connection. But what do you mean with that it shows you the _"ip address of last connected client"_? – Visual Vincent Aug 01 '18 at 10:10