TcpClient - get IP address

How do I get the IP address of a device that connects to a TcpListener?

Ive tried to do this two ways:

Dim listener as new TcpListener(IPAddress.Any, port)
Dim client as TcpClient = listener.AcceptTcpClient
'get IP that client is connected to?


Ive also tried this but cant figure out how to make a TcpClient from a Socket
Dim listener as new TcpListener(IPAddress.Any, port)
Dim socket as Socket = listener.AcceptSocket
'make a TcpClient from a Socket?

LVL 1
craigdevAsked:
Who is Participating?
 
gregoryyoungConnect With a Mentor Commented:
Public Class MyTcpClient
    Inherits TcpClient

    Public Sub New(ByVal s As Socket)
        Me.Client = s
        Me.Active = True
    End Sub

End Class

then your code would be

dim tcp as TcpClient = new MyTcpClient(socket)
0
 
gregoryyoungCommented:
of of course you would use acceptsocket, get you info THEN use this to make a tcpclient :)
0
 
checooCommented:
Dim listener as new TcpListener(IPAddress.Any, port)
Dim socket as Socket = listener.AcceptSocket

after this socket.RemoteEndPoint will give you the IP of the device connecting
0
 
Koala119Connect With a Mentor Commented:
how about try this:

        Dim listener As New TcpListener(IPAddress.Any, port)
        listener.Start()
        Dim socket As Socket = listener.AcceptSocket

        Dim ns As NetworkStream = New NetworkStream(socket)

        ' Get remote end point
        Dim remoteAddress As IPAddress = IPAddress.Parse(CType(socket.RemoteEndPoint, IPEndPoint).Address.ToString())

        ' Get local end point
        Dim localAddress As IPAddress = IPAddress.Parse(CType(socket.LocalEndPoint, IPEndPoint).Address.ToString())
0
 
gregoryyoungCommented:
checoo: I believe he knew this answer, the problem is once you have the socket creating a TCPClient from it :) based upon this.

"Ive also tried this but cant figure out how to make a TcpClient from a Socket
Dim listener as new TcpListener(IPAddress.Any, port)
Dim socket as Socket = listener.AcceptSocket
'make a TcpClient from a Socket?"

The problem is that for whatever reason they left the constructor that takes a socket off the TCPClient class (seems like a rather gross oversight to me)

Greg
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.