我从main调用setup_udp_socket方法,在udppport上设置UDP套接字然后我在这个套接字上使用select。当我有关于此方法的内容时,我会调用udp_communication()但我会收到奇怪的输出
[没有收到消息,即0字节但是char数组的strlen给出1]。 UDP数据包由另一个我无法访问的Java程序发送。我使用过nc并测试它运行良好。但是我的代码中似乎存在一些问题,我无法弄明白。
我在等待
listener:从127.0.0.1获得数据包,端口号:48555
收到的消息:字节数:0 len:1
退出udp_communication
int setup_udp_socket(char* udpport)
{
struct addrinfo hints, *servinfo, *p;
int ret_value;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
if ((ret_value = getaddrinfo("127.0.0.1", udpport, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret_value));
exit(FAILED);
}
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((udp_sock = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("udp: socket creation failed");
continue;
}
if (bind(udp_sock, p->ai_addr, p->ai_addrlen) == -1) {
close(udp_sock);
perror("udp: bind");
continue;
}
//listen(udp_sock, 20);
break;
}
if (p == NULL) {
if (servinfo != NULL)
freeaddrinfo(servinfo);
exit(FAILED);
}
freeaddrinfo(servinfo);
printf("udp: waiting to recvfrom and udpport :%s\n", udpport);
}
// udp_recvbuf是1024字节的char数组。
void udp_communication() {
struct sockaddr_storage addr;
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
int n;
addr_len = sizeof(addr);
//udp_sock_flag = fcntl(udp_sock, F_GETFL, 0);
//fcntl(udp_sock, F_SETFL, udp_sock_flag | O_NONBLOCK);
// while(1) {
memset(udp_recvbuf, '\0', BUFFERSIZE);
printf("I am waiting\n");
if (n = recvfrom(udp_sock, udp_recvbuf, 1023 , 0, (struct sockaddr *)&addr, &addr_len) == -1) {
perror("recvfrom");
exit(1);
}
printf("listener: got packet from %s and port number :%d\n ",
inet_ntop(addr.ss_family,
get_in_addr((struct sockaddr *)&addr),
s, sizeof s), ((struct sockaddr_in *)&addr)->sin_port);
printf("Message received:%s number of bytes : %d len: %d\n", udp_recvbuf, n, strlen(udp_recvbuf));
// }
printf("Exiting udp_communication\n");
//pthread_exit(NULL);
}