找回密码
 加入
搜索
查看: 2638|回复: 0

[网络通信] 通过ws2_32.dll发送UDP数据后,如何接收数据呢?

[复制链接]
发表于 2017-4-24 16:18:59 | 显示全部楼层 |阅读模式
场景:
Client(绑定指定端口)  -----UDP----->  Server
问题:如果使用ws2_32.dll来接收数据,Client如何接收Server响应的数据?哪位大虾帮忙做一个接收的函数。下面的代码是从AutoIT英文网上看到的。
ps:不能使用UDPSend,原因是UDPSend后,本地是随机端口,Server会向随机端口发包,导致脚本无法监听到数据。
UDPStartup()
$hWs2_32 = DllOpen("ws2_32.dll")

$hSocket = _WinsockCreateSocket(2, 2, 17)
_WinsockBind($hSocket, "192.168.0.241", 88); The source address and port for the Socket. The IP must be your LAN IP. I've found that 127.0.0.1 does not work.
_WinsockConnect($hSocket, "192.168.0.64", 5060); The destination IP and port.
_WinsockSend($hSocket, "SEND MSG!")

Func _WinsockCreateSocket($Address_Family, $Socket_Type, $Protocol)
    $iRet = DllCall($hWs2_32, "int", "socket", "int", $Address_Family, "int", $Socket_Type, "int", $Protocol)
    Return $iRet[0]
EndFunc

Func _WinsockBind($hSocket, $IP, $Port)
    $hAddr = _SocketAddr($IP, $Port)
    $iRet = DllCall($hWs2_32, "int", "bind", "uint", $hSocket, "ptr", DllStructGetPtr($hAddr), "int", DllStructGetSize($hAddr))
    Return $iRet[0]
EndFunc

Func _WinsockConnect($hSocket, $IP, $Port)
    $hAddr = _SocketAddr($IP, $Port)
    $iRet = DllCall($hWs2_32, "int", "connect", "uint", $hSocket, "ptr", DllStructGetPtr($hAddr), "int", DllStructGetSize($hAddr))
EndFunc

Func _WinsockSend($hSocket, $data)
    $hBuf = DllStructCreate("byte[" & BinaryLen($data) & "]")
    DllStructSetData($hBuf, 1, $data)
    $iRet = DllCall($hWs2_32, "int", "send", "uint", $hSocket, "ptr", DllStructGetPtr($hBuf), "int", DllStructGetSize($hBuf), "int", 0)
        If IsArray($iRet) Then _ArrayDisplay($iRet)
EndFunc

Func _SocketAddr($IP, $Port, $Address_Family = 2)
    $stAddress = DllStructCreate("short; ushort; uint; char[8]")
    DllStructSetData($stAddress, 1, $Address_Family)
    $iRet = DllCall($hWs2_32, "ushort", "htons", "ushort", $Port)
    DllStructSetData($stAddress, 2, $iRet[0])
    $iRet = DllCall($hWs2_32, "uint", "inet_addr", "str", $IP)
    DllStructSetData($stAddress, 3, $iRet[0])
    Return $stAddress
EndFunc   ;==>_SocketAddr

Func _WSAGetLastError()
    $iRet = DllCall($hWs2_32, "int", "WSAGetLastError")
    Return $iRet[0]
EndFunc   ;==>_WSAGetLastError
您需要登录后才可以回帖 登录 | 加入

本版积分规则

QQ|手机版|小黑屋|AUTOIT CN ( 鲁ICP备19019924号-1 )谷歌 百度

GMT+8, 2024-11-21 22:53 , Processed in 0.122647 second(s), 23 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表