求一linux接收udp广播程序(提供模板)

来源:百度知道 编辑:UC知道 时间:2024/06/07 12:14:02
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>

#define MYPORT 4950
main(int argc,char * argv[])
{

哥们,没bind你收啥?你又把my_addr传给recvfrom干啥(该传their_addr).
我给你写了个

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

int main()
{
int n, fd;
socklen_t cli_addr_len;
char buf[1024] = {0};
struct sockaddr_in servaddr, cliaddr;

if((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
printf("socket error!\n");
exit(0);
}

servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(9999);

bind(fd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while(1)
{
cli_addr_len = sizeof(cliaddr);
n =recvfrom(fd, buf, 1024, 0, (struct sockaddr *)&cliaddr, &cli_addr_len);
printf("%d\n", n);
}
}

这个程序只能收到发往本机IP地址和广播地址的端口为9999的数据包,如果你要监听局域网中的所有广播包(任意端口),可以用原始