我正在尝试创建UDP交互客户端/服务器。 我尝试使用此代码发送邮件时遇到了一些问题。 在执行过程中,我遇到了这个错误:
"协议不支持的地址族"在sendto功能之后。 提前谢谢!
int prepare_udp_socket(char *pong_addr, char *pong_port)
{
struct addrinfo gai_hints, *pong_addrinfo = NULL;
int ping_socket;
int gai_rv;
int np;
/*** Specify the UDP sockets' options ***/
memset(&gai_hints, 0, sizeof gai_hints);
gai_hints.ai_family=AF_INET;
gai_hints.ai_socktype=SOCK_DGRAM;
gai_hints.ai_flags=0;
gai_hints.ai_protocol = IPPROTO_UDP;
if ((ping_socket = socket(gai_hints.ai_family, gai_hints.ai_socktype, gai_hints.ai_protocol)) == -1)
fail_errno("UDP Ping could not get socket");
/*** change socket behavior to NONBLOCKING ***/
if(fcntl(ping_socket,F_SETFL, O_NONBLOCK)==-1)
fail_errno("set NONBLOCKING socket fail");
//call getaddrinfo() in order to get Pong Server address in binary form
gai_rv=getaddrinfo(pong_addr, pong_port, &gai_hints, &pong_addrinfo);
if(gai_rv!=0){
printf("Getaddrinfo failed\n");
exit(1);
}
/*** connect the ping_socket UDP socket with the server ***/
if(connect(ping_socket, pong_addrinfo->ai_addr, pong_addrinfo->ai_addrlen)!=0){
fail_errno("Can't connect");
}
freeaddrinfo(pong_addrinfo);
return ping_socket;
}
double do_ping(int msg_size, int msg_no, char message[msg_size], int ping_socket, double timeout)
{
int lost_count = 0;
char answer_buffer[msg_size];
ssize_t recv_bytes, sent_bytes;
int offset;
struct sockaddr_storage pong_addr;
size_t pong_addr_len = sizeof(struct sockaddr_storage);
struct timespec send_time, recv_time;
double roundtrip_time_ms;
int re_try = 0;
/*** write msg_no at the beginning of the message buffer ***/
if(sprintf(message,"%d\n",msg_no)<0){
fail("sprintf(...) failed");
}
do {
debug(" ... sending message %d\n", msg_no);
/*** Store the current time in send_time ***/
if(clock_gettime(CLOCK_MONOTONIC,&send_time)!=0){
fail_errno("clock_gettime failed with sendTime");
}
/*** Send the message through the socket ***/
**if((sent_bytes = sendto(ping_socket, &message, msg_size,0,(struct sockaddr*)&pong_addr,pong_addr_len)) == -1){
fail_errno("Cannot send bytes throught the socket");**
}
答案 0 :(得分:1)
问题出在你的do_ping
函数中,sendto
期望地址和长度为第5和第6个参数,它们是输入参数,这意味着,你需要指定目标主机的地址如果要将数据包发送到,则必须将地址初始化为有效地址。你在做什么就像'recvfrom`实际上。
此外,message
是指向函数内部char的指针,因此请勿在{{1}}中使用&message
,只需传递sendto
。
message