程序获取通过某个端口的UDP数据包
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h> //for sockaddr_in
#include <sys/types.h> //for socket
#include <sys/socket.h> //for socket
#include <string.h>
#define MAX_LEN 256
static const int ITEM_COUNT = 100;
int main()
{
int sock;
if((sock = socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("create socket error!");
return 0;
}
printf("socket sock=%d\n",sock);
struct sockaddr_in addr;
bzero(&addr,sizeof(addr));
addr.sin_family=AF_INET;
addr.sin_port=htons(13456);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
int r;
int fd = sock;
r=bind(fd,(struct sockaddr*)&addr,sizeof(addr));
if(r==-1)
{
printf("Bind error!\n");
close(fd);
exit(-1);
}
printf("Bind successfully.\n");
char buf[MAX_LEN];
struct sockaddr_in from;
socklen_t len;
len=sizeof(from);
while(1)
{
printf("准备接受数据··\n");
bzero(buf,sizeof(buf));
r=recvfrom(fd,buf,sizeof(buf),0,(struct sockaddr*)&from,&len);//成功则返回接收到的字符数,失败返回-1.
printf("收到的字符数为%d\n",r);
if(r<0)
{
break;
}
}
close(fd);
return 0;
}
发这个简单些的代码,想问个问题。我用tcpreplay指令:tcpreplay -c udp.cache -p 10 -i eth1 -l 0 rewrite.pcap重发数据包
然后使用tcpdump -i eth1 udp and host 127.0.0.1也是能看到数据包的
为什么程序运行到recvfrom()处就一直阻塞在那了,一个字符都不去接收。。。
明明有那么多UDP数据包,源和目的地址是127.0.0.1,端口号也是一致的。









