| tcp_stream - a TCP stream handle from OpenTCPStream or AcceptTCPStream |
|
Returns the port used by the machine at the other end of a TCP stream. The partner of TCPStreamIP: together they identify the far side of the connection completely. Which port you see depends on which end you hold. A stream from OpenTCPStream reports the server's well-known listen port - the one you dialled. A stream from AcceptTCPStream reports the connecting client's port, and that one is essentially random: clients connect FROM whatever free port their system hands them, TO the port the server advertises. The example prints both ends of a loopback connection so the asymmetry is plain to see. For a server, the far port is what separates two connections arriving from the same IP address - two players behind one router, or two copies of the game on one machine. IP plus port together are unique per connection; IP alone is not. The value is captured when the connection is made and doesn't change over the stream's life; if it could not be determined, the command returns 0. See also: TCPStreamIP, OpenTCPStream, AcceptTCPStream, CreateTCPServer, UDPMsgPort. |
; TCPStreamPort Example
; ---------------------
; This program is server AND client at once: it listens on a
; port, then connects to itself over the loopback address.
port=4007
server=CreateTCPServer(port)
If server=0 Then
Print "Could not listen on port "+port+" (it may be in use)"
Else
Print "Server: listening on port "+port
client=OpenTCPStream("127.0.0.1",port)
If client=0 Then
Print "Client: could not connect"
Else
; The server accepts the incoming connection - poll briefly,
; because AcceptTCPStream returns 0 until one has arrived
accepted=0
For try=1 To 100
accepted=AcceptTCPStream(server)
If accepted<>0 Then Exit
Delay 10
Next
If accepted=0 Then
Print "Server: no connection arrived"
Else
; TCPStreamPort returns the port of the OTHER end of the
; stream, so each side sees its partner's port number
Print "Client's stream: server's port = "+TCPStreamPort(client)+" (the listen port)"
Print "Server's stream: client's port = "+TCPStreamPort(accepted)+" (picked automatically)"
Print "Clients connect FROM a random free port, TO a known one"
CloseTCPStream accepted
EndIf
CloseTCPStream client
EndIf
CloseTCPServer server
Print "Server: closed"
EndIf
Print ""
Print "Press any key to close the example"
WaitKey
End