我想创建一个只向客户端发送数据的Winsock UDP套接字.我希望内核为我选择一个可用的端口.另一方面,我想指出要使用哪个本地IP,因为我正在运行一些nics.
我已经尝试梳理套接字选项的迷宫,以及与套接字地址设置为0的端口绑定无效.
我的代码是在Win32 C++中.
请原谅我没有错误检查:
char pkt[...]; size_t pkt_length = ...; sockaddr_in dest; sockaddr_in local; WSAData data; WSAStartup( MAKEWORD( 2, 2 ), &data ); local.sin_family = AF_INET; local.sin_addr.s_addr = inet_addr(
Graeme Perrow的答案不再适用,因为inet_addr已被弃用.使用inet_pton代替如下:
#include#include #include #pragma comment(lib, "ws2_32.lib") using namespace std; int main() { const char* pkt = "Message to be sent"; const char* srcIP = < source IP address >; const char* destIP = < destination IP address >; sockaddr_in dest; sockaddr_in local; WSAData data; WSAStartup(MAKEWORD(2, 2), &data); local.sin_family = AF_INET; inet_pton(AF_INET, srcIP, &local.sin_addr.s_addr); local.sin_port = htons(0); dest.sin_family = AF_INET; inet_pton(AF_INET, destIP, &dest.sin_addr.s_addr); dest.sin_port = htons(< destination port number >); SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); bind(s, (sockaddr *)&local, sizeof(local)); sendto(s, pkt, strlen(pkt), 0, (sockaddr *)&dest, sizeof(dest)); closesocket(s); WSACleanup(); return 0; }