使用UDP进行网络处理
问题描述:
使用sendto()将UDP数据包发送到主机时会发生什么情况。我发送的所有比特都被发送(从返回值中知道)。我立即使用recvfrom(),它不输出任何内容,但程序不退出(即不返回值)。使用UDP进行网络处理
我认为如果没有收到回复,程序必须退出。
对端口的UDP数据包的回复是什么。
这个包是被防火墙拦截的?如果是,那么为什么sendto的返回值是非负的。
答
recvfrom()
将阻塞,直到收到一条消息,除非您将套接字设置为非阻塞。
要查找的接口
-
ioctl()
与FIONBIO
或O_NONBLOCK
(根据您的平台), -
select()
等待数据的到达,超时一段时间后
另请注意,sendto()
的地址和端口号通常为网络字节顺序,因此请查看ntohl
和ntohs
。
答
您必须在客户端或服务器中出现错误。首先尝试使用localhost,这样可以避免出现防火墙问题
这是一个非阻塞udp客户端/服务器的示例,我用它来测试,它使用ioctl()检查是否有数据要读取到套接字上,但是如果你想用epoll的效率会比较高,你也可以指定超时微秒等待做一些重要的应用程序:
[[email protected] tests]$ cat udpserv.c
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#define BUFLEN 512
#define NPACK 15
#define PORT 9930
void diep(char *s)
{
printf("erno=%d errstr=%s\n",errno,strerror(errno));
perror(s);
exit(1);
}
int main(void)
{
struct sockaddr_in si_me, si_other;
int s,ret,nbytes, i, slen=sizeof(si_other);
char buf[BUFLEN];
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("socket");
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr*) &si_me, sizeof(si_me))==-1)
diep("bind");
fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0) | O_NONBLOCK);
sleep(10);
for (i=0; i<NPACK; i++) {
ret=ioctl(s,FIONREAD,&nbytes);
if (ret==-1) {
printf("error on FIONREAD\n");
} else {
printf("nbytes=%d\n",nbytes);
}
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr*) &si_other, &slen)==-1)
diep("recvfrom()");
printf("Received first half of packet from %s:%d\nData: %s\n\n",
inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
}
close(s);
return 0;
}
[[email protected] tests]$ cat udpclient.c
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define SRV_IP "127.0.0.1"
#define BUFLEN 200
#define NPACK 10
#define PORT 9930
/* diep(), #includes and #defines like in the server */
void diep(char *s)
{
perror(s);
exit(1);
}
int main(void)
{
struct sockaddr_in si_other;
int s, i, slen=sizeof(si_other);
char buf[BUFLEN];
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("socket");
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
for (i=0; i<NPACK; i++) {
printf("Sending packet %d\n", i);
sprintf(buf, "This is packet %d\n", i);
if (sendto(s, buf, BUFLEN, 0, (struct sockaddr*) &si_other, slen)==-1)
diep("sendto()");
}
close(s);
return 0;
}
和sendto()是非负的,因为它返回发送的字节数。检查sendto的手册页
你能分享一下你想做什么吗?你是否证实UDP是你想使用的协议? – bitops 2012-02-10 19:52:29