Get IP of incoming client - TCP - VB.Net - vb.net

I'm triyng to get the IP of an incoming client connection request :
1_ My computer scan all the IP in my network
2_ When it find a valid IP , it send to it a connection request
3_ The destination computer will have to get the IP of the client that is sending a connection request and create a
New TcpListener(ClientTriyngToConnectIP,64535)
So theres a way to get the IP of a client trying to connect to my computer ?

Finally i found a solution : this can be implemented in an application to get the IP of another computer trying to connect to your via TCP
To initialize the tcp listener :
Private InputClient As TcpClient
Public ConnectionRequestListener As TcpListener
Public sub Listener(IncomingPort as String)
Dim IPv4_Address As String = ""
For Each address In Dns.GetHostEntry(Dns.GetHostName()).AddressList
If address.AddressFamily = AddressFamily.InterNetwork Then
IPv4_Address &= address.ToString
Exit For
End If
Next
ConnectionRequestListener = New TcpListener(IPAddress.Parse(IPv4_Address), IncomingPort)
ConnectionRequestListener.Start()
end sub
Accept client :
InputClient = ConnectionRequestListener.AcceptTcpClient()
To get the IP of the client :
IPAddress.Parse((CType(ConnectionRequestListener.RemoteEndpoint,IPEndPoint)).Address.ToString()).ToString

Related

vb.net TCP where dose my faulty URL request go and where can I (if I can) find it?

I have a simple TCP/IP HTML server. To access this HTML server the user needs to type the IP address of the machine the HTML server is running on also, if the user types a faulty URL as long as it starts with the correct IP-address followed by a forward slash (example: 123.456.789.0/FaultyText) it also works.
My understanding is that if I type in a web browsers address bar it broadcasts that text-string till some server says "hey I recognize this, let me react upon it" meaning (according to my understanding) the opposite is also true if a text-string is broadcast which the server does not recognize it says "This I cannot identify, I'll pass reacting upon it". This would mean the text-string must always be read to know it's at the right destination or not.
So how come if I type something random in the URL address bar, the following code snippet won't reference to it in its HTTP headers Host:, or Refrence: sections (or anywhere else for that matter of fact)?
#Region "Start Server"
Dim MyIp As String
Dim MyPort As String
Try
'If Not MyNetworkPortBase64Plain = Nothing Then
' MyIp = MyNetworkIpBase64Plain
'Else
' Dim MyComputerName As String = Dns.GetHostName()
' MyIp = Dns.GetHostByName(MyComputerName).AddressList(0).ToString()
'End If
If Not MyNetworkPortBase64Plain = Nothing Then
MyPort = MyNetworkPortBase64Plain
Else
MyPort = "8080"
End If
MyIp = (IPAddress.Any).ToString
MyHtmlServer = New TcpListener(IPAddress.Parse(MyIp), MyPort)
MyHtmlServer.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf MyNewClientSub)
#Region "Server Start/ Stop Button"
#Region "Get/ Collect Incoming Bytes"
Dim MyNetworkStream As NetworkStream = MyClient.GetStream()
Dim MyReceivingBytes(100000) As Byte
MyNetworkStream.Read(MyReceivingBytes, 0, MyReceivingBytes.Length)
Dim MyIncommingRequests As String = Encoding.ASCII.GetString(MyReceivingBytes)
Dim webClient As New System.Net.WebClient
MsgBox(MyIncommingRequests)
#End Region
How can I catch all the URL requests made?

What is wrong with this code that should send some email with google?

Shared Sub sendMail(ByVal title As String, ByVal content As String)
Dim SmtpServer As New SmtpClient("smtp.gmail.com", 465)
SmtpServer.EnableSsl = True
SmtpServer.Credentials = New Net.NetworkCredential(username, password)
Dim mail As New MailMessage(username, username, title, content)
SmtpServer.Send(mail)
End Sub
I got the result of
System.Net.Mail.SmtpException: 'Failure sending mail.'
IOException: Unable to read data from the transport connection: net_io_connectionclosed.
What did I do wrong? Should I enable IMAP first at google?
My code is based on How do I send a gmail email in vb.net?
If I use port 587 instead of 465 I got
System.Net.Mail.SmtpException: 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at'
Using port 25 yield
SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.200.109:25
Using 465 yield the original error

It's posible to define the UDP sourceport?

I have a WinForm application made it in VB.NET and I need to answer in the same port that I receive the UDP message but with the code that I have running the application source port is being chosen by the O.S., or it seems that.
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
GLOIP = IPAddress.Parse(IpRemotaLbl.Text)
GLOINTPORT = RemotePortLbl.Text
MyUdpClient.Connect(GLOIP, GLOINTPORT)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
'Console.WriteLine("No of bytes send " & pRet)
PrintLog("No of bytes send " & pRet)
End Sub
In example, if I receive the UDP message on port 8082 the answer, currently, is being sent from port 1515(local) to 8082(remote) and I need to send the message from port 8082(local) to 8082(remote).
Thanks.
You need to bind the UdpClient to a local port before you call Send(). The only way to specify the source port is in the UdpClient's constructor, so if you do not know which source port to use until you have received a message first then you will have to wait until then before creating the UdpClient.
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
Dim MyUdpClient as UdpClient = new UdpClient(8082); ' <-- here
MyUdpClient.Connect(IPAddress.Parse(IpRemotaLbl.Text), RemotePortLbl.Text)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
'Console.WriteLine("No of bytes send " & pRet)
PrintLog("No of bytes send " & pRet)
End Sub

Socket programming over internet

I am making just a simple chat system using socket programming technique in vb.net .
It works fine on local network but how to use that over internet ..
I also try Port forwarding on my router ... May be my way is wrong .
Please tell me the correct way for port forwarding .. and tell me how to connect client to the server ???
Am i have to use a public IP of server system ???
the server side code is this :
Imports System.Net.Sockets
Module Module1
Sub Main()
Console.WriteLine("")
Dim clientListener As New TcpListener(12380)
clientListener.Stop()
clientListener.Start()
Console.WriteLine("")
Dim mySocket As Socket = clientListener.AcceptSocket()
Console.WriteLine("")
Dim recieveBuff(225) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
While Not str.StartsWith(".")
Console.WriteLine(str)
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
End While
Console.WriteLine("")
clientListener.Stop()
End Sub
End Module
and the client side code is this : (those both are console applications)
Imports System.Net.Sockets
Imports System.IO
Module Module1
Sub Main()
Try
Console.WriteLine("Connecting to localhost ")
Dim serverListener As New TcpClient("192.168.1.103", 12380)
Dim readStream As Stream = serverListener.GetStream
serverListener.SendBufferSize = 256
Console.WriteLine("Input Lines:")
Dim str As String = Console.ReadLine()
While 370
Dim sendBuff As Byte() = System.Text.Encoding.ASCII.GetBytes(str)
readStream.Write(sendBuff, 0, sendBuff.Length)
If str.StartsWith(".") Then
GoTo Done
End If
str = Console.ReadLine()
End While
Done: Console.WriteLine("Done")
Catch exp As Exception
Console.WriteLine("Exception: " + exp.ToString())
End Try
End Sub
End Module
You will need to use the public IP if the client is outside of your LAN.
First you need to enable port forwarding in the router, port should be lie between 49152 and 65535 and Address would be the private address of the server ex:"192.168.1.x"
Make sure you start listening your server in the new port (the one between 49152 and 65535)
then go to canyouseeme.org
and type the new port that you used and press check port
if the result was success than your configuration was correct and your server now is accessible via internet ,if the result was a red Error then you might done something wrong,probably a firewall problem, or you need to change the router.
if you get success then you must change this line in every client instead of the old one:
Dim serverListener As New TcpClient(YourPublicIpAdrees,NewPort)
To get your public ip address go here myip.
This is how to send a socket over internet, try it and comment your result.

TCP Server in VB.NET

I am not a software programmer but I have a task to create a TCP Server (a program that is listening on its network card interfaces for incoming data streams).
I have searched on the internet and I found that I can use two methods: Socket or TCPListener class.
I have created an example for the Socket class, but I was wondering how I can test it?
If another computer in the network sends some string data to the listener computer, then the message should be displayed.
Here is the example from Microsoft that I am using for the TCP server using a Socket:
Public Shared Sub Main()
' Data buffer for incoming data.
Dim data = nothing
Dim bytes() As Byte = New [Byte](1024) {}
Dim ipAddress As IPAddress = ipAddress.Any
Dim localEndPoint As New IPEndPoint(ipAddress, 0)
Dim intI As Integer = 0
'Display the NIC interfaces from the listener
For Each ipAddress In ipHostInfo.AddressList
Console.WriteLine("The NIC are {0}", ipHostInfo.AddressList(intI))
intI += 1
Next
Console.WriteLine("You are listening on {0}",localEndPoint)
' Create a TCP/IP socket.
Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Bind the socket to the local endpoint and
' listen for incoming connections.
Try
listener.Bind(localEndPoint)
listener.Listen(200)
Catch e As SocketException
Console.WriteLine("An application is alreading using that combination of ip adress/port", e.ErrorCode.ToString)
End Try
' Start listening for connections.
While True
Console.WriteLine("Waiting for a connection...")
' Program is suspended while waiting for an incoming connection.
Dim handler As Socket = listener.Accept()
data = Nothing
' An incoming connection needs to be processed.
While True
bytes = New Byte(1024) {}
Dim bytesRec As Integer = handler.Receive(bytes)
data += Encoding.ASCII.GetString(bytes, 0, bytesRec)
Console.WriteLine("The string captured is {0}", data)
If data.IndexOf("something") > -1 Then
Exit While
End If
End While
' Show the data on the console.
Console.WriteLine("Text received : {0}", data)
' Echo the data back to the client.
Dim msg As Byte() = Encoding.ASCII.GetBytes(data)
handler.Shutdown(SocketShutdown.Both)
handler.Close()
End While
End Sub
End Class
Am I on the right lead?
Thanks
Later Edit:
I have used that code in a Console Application created with Visual Studio and I want to check the scenario when a device is sending some string message through the network.
E.g:
I have two devices :Computer A, computer B connected through LAN
I have tried this command : telnet computerA port ( from computer B) but nothing is displayed in the TCP server running from computer A.
telnet 192.168.0.150 3232
I also made a TCP client for testing (derived from the Microsoft example):
Public Class SynchronousSocketClient
Public Shared Sub Main()
' Data buffer for incoming data.
Dim bytes(1024) As Byte
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New IPEndPoint(ipAddress, 11000)
' Create a TCP/IP socket.
Dim sender As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Connect the socket to the remote endpoint.
sender.Connect(remoteEP)
Console.WriteLine("Socket connected to {0}", _
sender.RemoteEndPoint.ToString())
' Encode the data string into a byte array.
Dim msg As Byte() = _
Encoding.ASCII.GetBytes("This is a test<EOF>")
' Send the data through the socket.
Dim bytesSent As Integer = sender.Send(msg)
' Receive the response from the remote device.
Dim bytesRec As Integer = sender.Receive(bytes)
Console.WriteLine("Echoed test = {0}", _
Encoding.ASCII.GetString(bytes, 0, bytesRec))
' Release the socket.
sender.Shutdown(SocketShutdown.Both)
sender.Close()
Console.ReadLine()
End Sub
End Class 'SynchronousSocketClient
But it does not work because of the PORT setting.
If in the TCP Server I have "Dim localEndPoint As New IPEndPoint(ipAddress, 0)" then the client crashes, but if I change the port from any (0) to 11000 for example, the client works fine.
Do you know why?
Later edit 2:
Maybe I should have started with this question: Which method is recommended for my scope - asynchronous or synchronous method?
Yes, you are on the right path.
The next thing to do is to introduce message detection since TCP is stream based and not message based like UDP. This means that TCP might decide to send two of your messages in the same packet (so that one socket.Recieve will get two messages) or that it will split up your message into two packets (thus requiring you to use two socket.Recieve to get it).
The two most common ways to create message detection is:
Create a fixed size header which includes message size
Create a delimiter which is appended to all messages.
Your "server" isn't listening on a set port, so you'll need to pay attention to the "You are listening on" message that appears. Then, from another machine on the network, telnet the.ip.add.ress port. (This may require installing "telnet client", or enabling it in the Programs and Features stuff, or whatever.)
Side note...if you actually intend for this to be a server of some sort, you'll want to decide what port you want to use, so that other computers can find your service. Most people won't be able to read your screen to figure out where to connect. :)
As for your "client"...when you connect to another computer, you don't just "pick a port" (which is what a port number of 0 means in an endpoint). You need to know what port the server uses. (Reread what i said in the previous paragraph. A program running on another computer has no idea what port to use to connect to the server -- any server could be running on any port.) You need to pick a port number for the server (say, 11000...good as any, really) rather than letting it use port 0.