Open a port with vb? [closed] - vb.net

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can anyone please share a simple code for VB 2008 to open a port. I would like it to be just like utorrent how you can change the listening port for data transfer. thanks a lot if you can help me!

As Avner indicated, uTorrent is not simple code. If you'd like to do anything on that level, then you've got a lot to do.
Here is a simple sample socket program you can build on.
Imports System.Net
Imports System.Net.Sockets
Module Module1
Sub Main()
Console.WriteLine("Enter the host name or IP Address to connect to:")
Dim hostName = Console.ReadLine().Trim()
If hostName.Length = 0 Then
' use the local computer if there is no host provided
hostName = Dns.GetHostName()
End If
Dim ipAddress As IPAddress = Nothing
' parse and select the first IPv4 address
For Each address In Dns.GetHostEntry(hostName).AddressList
If (address.AddressFamily = AddressFamily.InterNetwork) Then
ipAddress = address
Exit For
End If
Next
' you will have to check beyond this point to ensure
' there is a valid address before connecting
Dim client = New TcpClient()
Try
' attempt to connect on the address
client.Connect(ipAddress, 80)
' do whatever you want with the connection
Catch ex As SocketException
' error accessing the socket
Catch ex As ArgumentNullException
' address is null
' hopefully this will never happen
Catch ex As ArgumentOutOfRangeException
' port must be from 0 to 64k (&HFFFF)
' check and ensure you've used the right port
Catch ex As ObjectDisposedException
' the tcpClient has been disposed
' hopefully this will never happen
Catch ex As Exception
' any other exception I haven't dreamt of
Finally
' close the connection
' the TcpClient.Close() method does not actually close the
' underlying connection. You have to close it yourself.
' http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B821625
client.GetStream().Close()
' then close the client's connection
client.Close()
End Try
End Sub
End Module
Be aware that socket programming is quite complicated and you will have to thoroughly test your code for all edge cases.
Good luck!

uTorrent is anything but a "simple code". It's a complicated application with a lot of network logic going on beyond just opening a port and pushing bits in and out of it.
But your starting point for low-level communications handling would be the System.Net.Sockets namespace, which contains the Socket class. It allows low-level control such as opening a port, listening for connections and handling them yourself.
Here's a tutorial about Socket programming in VB.NET, but you'll probably find more information if you search for "C# Socket tutorial". C# syntax is a bit different than VB.NET, but it uses the same classes and the same concepts, so you'll probably be able to apply the lessons to your own code.

Related

How to solve Socket Accept Timeout [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a power on-off device to control. If the device is connected to the network, my code works fine. I remove the device from the network on purpose to test it as if the device malfunctions (like power off). And I find out that the System hangs.
I trace that the socket.accept does not execute - 'accept is ok' is not written to a log file. ex.message does not write as well.
My purpose is to send a message to support if there is any device malfunction.
Using gSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
WriteLog("Start. ")
Dim remoteSocket As Socket
Try
gSocket.SendTimeout = 5000
gSocket.ReceiveTimeout = 5000
gSocket.Bind(vEndPoint) ' vEndpoint is the local machine
WriteLog("bind is ok. ")
gSocket.Listen(10)
WriteLog("listen is ok. ")
remoteSocket = gSocket.Accept
WriteLog("accept is ok. ")
Catch ex As Exception
WriteLog(ex.Message)
Finally
End Try
How can I solve this?
I use BeginAccept to solve it.
Dim acceptResult As IAsyncResult = gSocket.BeginAccept(Nothing, Nothing)
Dim Success As Boolean = acceptResult.AsyncWaitHandle.WaitOne(vTimeout, True)
If Success Then
remoteSocket = gSocket.EndAccept(acceptResult)
WriteLog("beginaccept is ok. ")
Else
gSocket.Close()
WriteLog("beginaccept failed. ")
End If

TCP/IP Messaging Application VB.net - IP Address / Port-Forwarding Questions

I am developing a piece of scientific software in VB.net that I intend to distribute. Part of the application will involve communication with a server (and other clients). For all intents and purposes the communication will be like a chat application.
I have developed the software using sockets, and it works fine when testing at home on my local network. Below is basically how I send messages:
Dim serverIPString as String = "192.168.1.5"
Dim serverPort as long = 65500
dim messageString as String = "Hello"
Dim Client As New System.Net.Sockets.TcpClient(serverIPString, serverPort)
Dim Writer As System.IO.StreamWriter(Client.GetStream())
Writer.Write(messageString)
Writer.Flush()
Writer.Close()
And this is how I listen:
Public Class TCPIPListener
Dim initalised As Boolean = False
Dim port As Long
Dim IP As System.Net.IPAddress
Dim ourListener As TcpListener
Dim ourClient As TcpClient
Dim ourMessage As String
'''''''''''
'' ctors ''
'''''''''''
Public Sub New()
initalised = False
End Sub
'Takes IP and port and starts listeing
Public Sub New(inIP As String, inPort As Long, inExchange As messageExchange)
'Try to set the IP
Try
IP = System.Net.IPAddress.Parse(inIP)
Catch ex As Exception
Exit Sub
End Try
'Set the port
port = inPort
initalised = startListener()
End Sub
'''''''''''''''
'' Listening ''
'''''''''''''''
Private Sub Listening()
ourListener.Start()
End Sub
'starts listener
Public Function startListener() As Boolean
ourListener = New TcpListener(IP, port)
ourClient = New TcpClient()
Dim ListenerThread As New Thread(New ThreadStart(AddressOf Listening))
ListenerThread.Start()
initalised = True
Return True
End Function
'Called from a timer on the form
Public Function tick() As Boolean
If Not initalised Then
Return False
End If
If ourListener.Pending = True Then
ourMessage = ""
ourClient = ourListener.AcceptTcpClient()
Dim Reader As New System.IO.StreamReader(ourClient.GetStream())
While Reader.Peek > -1
ourMessage = ourMessage + Convert.ToChar(Reader.Read()).ToString
End While
messagebox(ourMessage)
End If
Return True
End Function
End Class
Using this approach, every client will be listening for messages sent from the server, and any messages sent will go to the server and be directed to the relevant client - it's a little inefficient but necessary for the way my software works.
The problem is that I am having real trouble getting this to work across the internet. If I send a message to a local IP address it works fine, even from the debugger. If I use a external IP address I get the following:
No connection could be made because the target machine actively refused it XXX.XXX.XXX.XXX:65500"
I have turned on port forwarding with my router and set up the correct port (65500 here) to forward to my PC running the lister (192.168.1.5) for both TCP and UDP. This website it tells me this port is open, and those either side are not.
If I right click on the exe and run as administrator, my antivirus pops up and says it is doing something suspicious when I start the listener (which I guess if anything is encouraging). If I then add my application to the list of exceptions and run it again, then check to see if the port is listening (using this) I find my application listening on the correct port (if I stop the application it is gone). However the client application still gives the same error above. If I use a random IP address rather than the one of the listener I get a different error:
{"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 XXX.XXX.XXX.XXX:65500"}
I suspect I am not taking the correct approach to this. I am fine with most aspects of VB, but have not really tackled this sort of problem before. When it comes to distributing software I really don't want my customers to have to mess around with deep settings to get this application to work. Any help will be immensely useful to me!
Another problem I guess I will face in the future is if multiple clients have the same external IP but different internal IPs (I intend to distribute to universities). Under these circumstances I guess port forwarding will not work.
Thanks very much in advance (and apologies for the long post)!
If you set your server to listen for connections on 192.168.1.5 then it will only allow connections from that specific IP address. The address you give a TcpListener is the IP address which you will accept connections from.
Since the 192.168.1.5 address is internal no one outside your network will be able to connect to your server. Make your server listen to 0.0.0.0 (or the equivalent IPAddress.Any) instead to make it allow connections from anyone.

vb.net USB Port Name/Description

I already acquired the code for Name of the modem. But I don't know how to use WMI because I can't really understand how does it works. For now, the code for it is so complicated.
Can you guys help me regarding to name my port? It's RFID Reader and it's USB Port. Look for the image as reference.
This image will show you that in Left Side < I got my COM 7 port in Modem but In right side > I got many option to pick, because my modem opens many port. I need to know how to name my other port(RFID COM PORT) so that I dont need to guess what is the right port for it.
Try
Dim searcher As New ManagementObjectSearcher( _
"root\cimv2", _
"SELECT * FROM Win32_SerialPort")
For Each queryObj As ManagementObject In searcher.Get()
MsgBox(queryObj("Name"))
enter code here
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
So, I change the code, and I just want the system to message me what is the open port. But, unfortunately, My RFID (Profilic USB-to-Serial Comm Port (COM3) is not being shown.
Edit
This is the output messagebox, well as you can see guys, there's no profilic. Even though it's been plugged, and seen by Device Manager.
But If I change the code to Win32_PnPEntity it will show all peripherals, and etc. and eventually It will show the Image

Winsock in VB.net not working

Hey all i am trying to get this code that worked in VB6 just fine to work in VB.net 2008. It doesnt seem to want to connect (but has no error after it goes past the sockMain.Connect().
sockMain.RemoteHost = "192.168.1.77"
sockMain.RemotePort = 77
sockMain.Connect()
Now when i do this:
On Error GoTo oops
sockMain.SendData(txtSend.Text)
oops:
If Err.Number = 40006 Then
MsgBox("It doesnt seem that the server is running. Please check it and try again")
End If
I get the It doesnt seem that the server is running. Please check it and try again. error.
What am i missing??
David
As I explained in a comment, VB.NET and VB 6 are almost entirely different programming languages. You're not doing yourself any favors by trying to write VB 6 code in VB.NET. There's no reason to migrate at all if you're not going to take advantage of the new features provided by the .NET platform.
Beyond the structured exception handling that I mentioned already, you should ditch the old WinSock control in favor of the classes found in the System.Net.Sockets namespace.
Try replacing what you have with something like the following code:
Dim tcpClient As New System.Net.Sockets.TcpClient()
tcpClient.Connect("192.168.1.77", 77)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim returnData As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("Host returned: " + returnData))
Else
If Not networkStream.CanRead Then
Console.WriteLine("Cannot not write data to this stream. " &
"Please check the server and try again.")
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
Console.WriteLine("Cannot read data from this stream. " &
"Please check the server and try again.")
tcpClient.Close()
End If
End If
End If
if you want the feeling of the vb6 winsock in .net world try this, beware it was not updated since 2008 and there is a few bug, look at the comment at the end of the acticle for more information
The Connect call can take a little while to complete. Even if your client has made the physical connection to the server, you have to give it a wee while to establish the TCP virtual circuit. If you put a breakpoint on the call to SendData and wait just a second or two, then continue, you'll probably find that it works OK.

Strange socket problems

I have a server I wrote using Asynchronous sockets. In the piece that accepts new connections I am getting a problem where some users are saying that some of the times they get this error on the server when the client tries to re-connect to the server:
"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"
After this error occurs the server goes dead and no new clients can connect until I physically quit the server program and start it again. So what should I do when I get this error? I tried to essentially restart the server in my code by closing the socket (listener.Close()) and then calling the same code I used to create and bind to the socket in the beginning, but then I get an error saying that I can't bind to the same port again.
So, two questions. First off, what is the proper way to handle that error and prevent it from essentially killing my server? Next, what is the proper way to restart a server through my code? Just calling .close() on the listener and then starting it again doesn't work in this case.
Thanks
Here is the code that accepts the connection request
Private Sub connectionRequest(ByVal ar As IAsyncResult)
Try
Dim thisListener As Socket = CType(ar.AsyncState, Socket)
Dim handler As Socket = thisListener.EndAccept(ar)
Dim remoteEndPoint As IPEndPoint
remoteEndPoint = handler.RemoteEndPoint
thisListener.Listen(10)
thisListener.BeginAccept(New AsyncCallback(AddressOf connectionRequest), thisListener)
thisListener.NoDelay = True
thisListener.Ttl = 32
Dim state As New StateObject
state.workSocket = handler
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf dataArrival), state)
handler.NoDelay = True
Catch ex As Exception
End Try
End Sub
Could you show us the code that you have for accepting connections?
You shouldn't have to restart your server. You should just fix the bug in your accept code in your server.
Clients can and will experience this problem when a server isn't accepting connections quickly enough, and/or if the listen backlog queue is too short for the rate at which new connections are being established and at which the server is accepting them.