【发布时间】:2015-02-13 01:28:32
【问题描述】:
我有一个函数,每次我想发送 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);
}
【问题讨论】:
-
perror()究竟打印了什么? -
发送到错误:erno 0x23
-
真的吗?没有错误文字?那么 0x23 是 35 也就是
EDEADLCK.你可能会从不同的线程调用它吗? -
UDP 套接字通常打开:socket(AF_INET, SOCK_DGRAM, 0)