嗨,我最近开始对 UDP 套接字进行编程,并且一直在将它们用于本地网络上的各种东西。但我似乎找不到任何关于如何在我可爱的防火墙之外发送 UDP 数据包的信息。
这是我用于绑定 UDP 套接字的代码
int handle = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( (unsigned short) /* port */);
bind( handle, (const sockaddr*) &address, sizeof(sockaddr_in) )
这是我用来发送数据包的代码
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl( /*local network IP Address*/ );
address.sin_port = htons( (unsigned short) /* port */ );
sendto( handle, (const char*)/* packet data */, size, 0, (sockaddr*)&address, sizeof(sockaddr_in) );
最后是我用来接收数据包的代码
sockaddr_in from;
socklen_t fromLength = sizeof( from );
int received_bytes = recvfrom( handle, (char*)data, size, 0, (sockaddr*)&from, &fromLength );