![](/img/trans.png)
[英]How can I use the same UDP socket both for sending and receiving packets? What am I missing in this code?
[英]How to correctly reuse a socket for sending UDP packets?
我有一個函數,每次要發送UDP數據包時都會被調用。
如果我采取以下步驟,一切都會很好:
但是,我不想每次調用該函數時都要不斷創建套接字的開銷。
有沒有一種首選的方式來解決這個問題? 我只想創建一次套接字,然后繼續重復使用它。 我嘗試通過引入“ first_time”標志來做到這一點-但是當我采用這種方法時,sendto()函數以errno 0x23開始失敗。
由於我在VxWorks中工作,因此我不清楚該錯誤代碼是ENOTSUP(VxWorks錯誤代碼)還是EWOULDBLOCK(發送錯誤代碼)。 無論哪種方式,我都無法解決。
請參閱下面的代碼。
/* Global Scope */
int send_socket = 0;
int first_time = 1;
void myFunction(...)
{
if (first_time == 1)
{
first_time = 0;
send_socket = socket(PF_INET , SOCK_RAW , IPPROTO_UDP);
if(send_socket < 0)
perror("socket() error");
/* Inform the kernel do not fill up the packet structure. */
/* We will build our own... */
if(setsockopt(send_socket, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0)
perror("setsockopt() error");
}
// ... populate buffer ...
if(sendto(send_socket,
*buffer,
my_ip_header->total_length,
0,
(struct sockaddr *)&sin,
sizeof(sin)) < 0)
{
perror("sendto error");
}
// Normally I'd close the socket right here...
// But I don't want to do this, because I want to use it later!
// close(send_socket);
}
您使用的是原始套接字,而不是您所說的UDP。 創建套接字時,請嘗試使用SOCK_DGRAM標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.