#include 'array.au3'
TCPStartup()
Global Const $__TCP_WINDOW = GUICreate('')
Global $hWs2_32 = -1
_TCP_Server_Create(0, '0.0.0.0')
MsgBox(4096, '', '现在服务端创建的TCP连接使用的端口是?该如何获取呢?')
While 1
Sleep(100)
WEnd
Func _TCP_Server_Create($iPort, $sIP = "0.0.0.0")
$hListenSocket = _ASocket()
_ASockSelect($hListenSocket, $__TCP_WINDOW, 0x0400, 8)
_ASockListen($hListenSocket, $sIP, $iPort)
Return $hListenSocket
EndFunc ;==>_TCP_Server_Create
Func _ASocket($iAddressFamily = 2, $iType = 1, $iProtocol = 6)
If $hWs2_32 = -1 Then $hWs2_32 = DllOpen("Ws2_32.dll")
Local $hSocket = DllCall($hWs2_32, "uint", "socket", "int", $iAddressFamily, "int", $iType, "int", $iProtocol)
If @error Then
SetError(1, @error)
Return -1
EndIf
If $hSocket[0] = -1 Then
SetError(2, _WSAGetLastError())
Return -1
EndIf
Return $hSocket[0]
EndFunc ;==>_ASocket
Func _ASockSelect($hSocket, $hWnd, $uiMsg, $iEvent)
If $hWs2_32 = -1 Then $hWs2_32 = DllOpen("Ws2_32.dll")
Local $iRet = DllCall($hWs2_32, "int", "WSAAsyncSelect", "uint", $hSocket, "hwnd", $hWnd, "uint", $uiMsg, "int", $iEvent)
If @error Then
SetError(1, @error)
Return False
EndIf
Return True
EndFunc ;==>_ASockSelect
Func _ASockListen($hSocket, $sIP, $uiPort, $iMaxPending = 5)
Local $iRet
Local $stAddress
If $hWs2_32 = -1 Then $hWs2_32 = DllOpen("Ws2_32.dll")
$stAddress = __SockAddr($sIP, $uiPort)
If @error Then
SetError(@error, @extended)
Return False
EndIf
$iRet = DllCall($hWs2_32, "int", "bind", "uint", $hSocket, "ptr", DllStructGetPtr($stAddress), "int", DllStructGetSize($stAddress))
If @error Then
SetError(3, @error)
Return False
EndIf
If $iRet[0] <> 0 Then
$stAddress = 0
SetError(4, _WSAGetLastError())
Return False
EndIf
$iRet = DllCall($hWs2_32, "int", "listen", "uint", $hSocket, "int", $iMaxPending)
If @error Then
SetError(5, @error)
Return False
EndIf
If $iRet[0] <> 0 Then
$stAddress = 0
SetError(6, _WSAGetLastError())
Return False
EndIf
Return True
EndFunc ;==>_ASockListen
Func __SockAddr($sIP, $iPort, $iAddressFamily = 2)
Local $iRet
Local $stAddress
If $hWs2_32 = -1 Then $hWs2_32 = DllOpen("Ws2_32.dll")
$stAddress = DllStructCreate("short;ushort;uint;char[8]")
If @error Then
SetError(1, @error)
Return False
EndIf
DllStructSetData($stAddress, 1, $iAddressFamily)
$iRet = DllCall($hWs2_32, "ushort", "htons", "ushort", $iPort)
DllStructSetData($stAddress, 2, $iRet[0])
$iRet = DllCall($hWs2_32, "uint", "inet_addr", "str", $sIP)
If $iRet[0] = 0xffffffff Then
$stAddress = 0
SetError(2, _WSAGetLastError())
Return False
EndIf
DllStructSetData($stAddress, 3, $iRet[0])
Return $stAddress
EndFunc ;==>__SockAddr
Func _WSAGetLastError()
If $hWs2_32 = -1 Then $hWs2_32 = DllOpen("Ws2_32.dll")
Local $iRet = DllCall($hWs2_32, "int", "WSAGetLastError")
If @error Then
ConsoleWrite("+> _WSAGetLastError(): WSAGetLastError() failed. Script line number: " & @ScriptLineNumber & @CRLF)
SetExtended(1)
Return 0
EndIf
Return $iRet[0]
EndFunc ;==>_WSAGetLastError