VB.Net checking if a port is open and accepting connections - vb.net

I'm writing a VB.Net app which connects to a remote server and listens for data on that port.
I've got the following function which checks that the IP/port in question is listening for connections or not. When the process on the remote port is running is works fine but when it's not running rather than the exception handler running I get an ugly dialogue box in Visual Studio rather when I run it.
Any ideas why the exception handler is not firing ?
Private Function testSelectedPort(ip As String, port As Integer) As Boolean
' Function to open a socket to the specified port to see if it is listening
' Connect to socket
Dim testSocket As New System.Net.Sockets.TcpClient()
Try
testSocket.Connect(ip, port)
' The socket is accepting connections
testSocket.Close()
Return True
Catch ex As Exception
' The port is not accepting connections
Return False
End Try
Return False
End Function
The error that's being thrown in "No connection could be made because the target machine actively refused it" and it's being thrown at the testSocket.Connect(ip, port) line.
I thought that it would execute the code in the Catch section if it failed to connect ?

Once the exception is thrown it should be handled by the Catch-block. There are only a few exceptions that are generally not very easy to handle via Try/Catch (for instance a System.AccessViolationException), but those do not include the errors a socket might throw.
Please make sure that you haven't ticked the specific exception type to break when thrown, in the Exception Settings window

Related

Visual basic UploadFile cannot connect to remote server

I tried to upload file via Visual Basic with UploadFile function.
In documentation I found this step:
My.Computer.Network.UploadFile(
"C:\My Documents\Order.txt",
"http://www.cohowinery.com/upload.aspx", "anonymous", "")
I tried it by myself, it works, but when the FTP ports (20,21) are disabled, it cannot works, and take an error, that is normal I know, but how to fix it? How to check the ports or, check the connection to FTP server before connection?
Generally I use:
If My.Computer.Network.IsAvailable Then...
but this works only with general of internet connection.
Any suggestions how to edit my code, to take down any error?
A simple Try/Catch should work.
Try
My.Computer.Network.UploadFile("","","","")
Catch ex As Exception
'Error happened
End Try

VisM with VB.net Connection "Server Receive Timed Out"

I added a VisM control into vb.net via adding a reference to VisM.ocx and adding it in my toolbox as an activeX control.
I added the following code in a button:
Try
'open the connection
AxVisM1.Connect("CN_IPTCP:127.0.0.1[57772]", "LIVEDATA")
'do stuff.
MsgBox("Cache is now active")
'close the connection
AxVisM1.DeleteConnection()
Catch ex As Exception
'close the connection
AxVisM1.DeleteConnection()
MsgBox(ex.ToString)
End Try
however when I run the application the connection hangs, followed by a messagebox that says "Server Receive Timed Out".
I have tried turning off my firewall, and even my antivirus. How will I resolve this? Also, is what I am trying an effective way to access GLOBALS variables in VB.net??
I'm not familiar with VisM, but you using wrong port, and this port only for web, try to change it to 1972, which is used by default. Your server may use another one. Your real port number you can find at System Management Portal on page About (link in the header), and parameter is - Superserver Port.

how can a network programming solution be tested at home?

I have a program used for the online multi-playing of sudoku (don't ask). I have written the code devoted to setting up specific tcpclient connections between instances of the application but when I tried to test it using the local host (IP:127.0.0.1) I got the error message:
"no connection could be made because the target machine actively refused it"
just when trying to set-up the client. regardless, it uses the same port to listen as to send and so later on this method would run into trouble but i need to test my solution so i ask: what is the easiest way (time is a factor) to test a network program at home. i have access to the following:
1 computer with the database installed via xampp (database is necessary)
up to 2 other computers without the database (could maybe be installed)
thank you.
edit:
'sets the destination IP to the HostAddress
IP = sender.CurrentRow.Cells.Item("HostAddress").Value
'creates a new instance of a client for send and recieving streams
client = New TcpClient(IP, port)
this is how I initialise the client. it is in the sub that a datagridview cell is clicked and HostAddress contains the IP address of the host as a string. it is the second line where the exception happened.
You provided too little information to actually help you find a bug, but here is how you can try if a basic connection on localhost works on your PC. Create two console projects, one the client and one server and insert the following code:
Client
Imports System.Net.Sockets
Imports System.Net
Module Client
Sub Main()
Dim IP As IPAddress = IPAddress.Parse("127.0.0.1")
Console.WriteLine("Start server and then press any key to connect.")
Console.ReadKey()
Console.WriteLine("Connecting...")
Dim client As New Net.Sockets.TcpClient
client.Connect(IP, 6583)
Console.WriteLine("Connected!")
Console.ReadKey()
client.Close()
End Sub
End Module
Server
Imports System.Net.Sockets
Imports System.Net
Module Server
Sub Main()
Dim IP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim server As New TcpListener(IP, 6583)
server.Start()
Console.WriteLine("Waiting for connection...")
While server.Pending = False
End While
Dim connectedclient As TcpClient = server.AcceptTcpClient
Console.WriteLine("Client connected. Nice.")
Console.ReadKey()
End Sub
End Module
Compile and start the projects. Once the server starts it starts listening on port 6583 on localhost. Start the client and press a key and you should see messages saying that the connection works.
If it does, you code is faulty. If it doesn't you should check your firewall settings and stuff like this.

TcpListener actively refused connection

I am maintaining an application that uses a TcpListener to listen for incoming communication. The following code opens the connection:
Dim listener As TcpListener
_listenFailed = False
Try
listener = New TcpListener(System.Net.IPAddress.Parse(Me.Host), Me.Port)
listener.Start()
Catch ex As Exception
' an error here means the settings are likely bogus
_listenFailed = True
Return
End Try
While Not _stoplistening
{
' Accept connection
}
The problem that I am having is that when i send a file from a different computer, I get the error "No connection could be made because the target machine actively refused it."
I have checked for firewalls and antivirus, and there were no blocks. I used
netstat -a -n
to determine that the port is active and listening. Both applications are running from Visual Studios in Administrator mode, not that this should make a difference. I have a break point set at the first line of the accept connection code, but it never gets run.
I stopped the application and examined the TcpListener, and found that there were a couple errors if I dug deep down. At TcpListener.LocalEndpoint.IPEndPoint.IPAddress.Address.ErrorCode there was the error 10045, "OperationNotSupported". Also, at TcpListener.Socket.RemoteEndPoint.ErrorCode there was an error 1057, "A request to send or receive data was disallowed because the socket is not connected, and (when sending on a datagram socket using a sendto call) no address was supplied. I don't know if either of these errors are relevant.
If anyone has any insights as to what might be causing this problem, or steps that can be taken to trace the root of the issue, I would be grateful.
Try changing this:
listener = New TcpListener(System.Net.IPAddress.Parse(Me.Host), Me.Port)
To this:
listener = New TcpListener(System.Net.IPAddress.Any, Me.Port)
This will allow you to listen across all network interfaces.
Additionally, you can use IPv6Any instead of Any if you want to target IPv6 instead. This choice has an impact on the address used by the client side obviously.

Difference between new TcpClient(MachineName, port) and new TcpClient(new IPEndpoint(..., Port))

Hej Hej,
I have a .Net program that has to run on a cluster of server 2008.
To find out the right IP I resolve the dns by
GetHostEntry(VarDefinedInfConfig).AddressList(0)
but when I am converting my old code (this code picks the wrong IP) dns.GetHostName().AddressList(0) => this returns a virtual IP and not the right one.
So I changed my TcpListener to (dns is parameter from config)
Dim listener As TcpListener = New TcpListener(New IPEndPoint(Net.Dns.GetHostEntry(dns).AddressList(0), 8001))
listener.Start()
In the old way a tcpclient was defined by this code
Dim client As TcpClient = New TcpClient(Environment.MachineName, 8001)
Console.WriteLine("Done...")
client.Close()
This also connects to the wrong IP so I found the overload of TcpClient and used that one
New way:
Dim client2 As TcpClient = New TcpClient(New IPEndPoint(Net.Dns.GetHostEntry(dns).AddressList(0), 8001))
Console.WriteLine("Done")
client2.Close()
But when I use the second one I got the exception "Only one usage of each socket address (protocol/network address / port) is normally permitted.
Weird thing is if I get the IP from the MachineName is exactly the same as the ip retreived from dns with parameter.
Does anybody know the cause of this exception? Normally they should have the same result.
Greetz,
Jonathan
Is it possible that you overlooked the main difference between the 2 mentioned TcpClient constructors (MSDN)?:
TcpClient(String, Int32) .. connects to the specified port on the specified host.
TcpClient(IPEndPoint) .. binds it to the specified local endpoint.
So effectively, with the first constructor a socket is opened on an available, "OS-assigned" local port and then connected to the server, whose address or DNS-name and port are passed in as arguments; after that you're ready to send or receive data.
With the second constructor a socket is just opened on a certain local port (which is identified in the endpoint argument), but that's all - no connection to any [remote, or even local] server is made, because no server info is known yet; you'd need to call one of Connect(.) methods before making any comm operations (similar to the workaround you found).
Why don't you specify the correct IP in the application config?
Only one usage of each socket address (protocol/network address / port) is normally permitted
Means that someone (your or another application) is already listening on that ip/port.
Right now I use an work arround. I create an TcpClient() with an empty constuctor and then I use the Connect(IPendpoint) and this works.