为什么我的C语言程序收不到广播包。而且recvfrom的返回值是-1(出错) 10
#include<winsock2.h>#include<stdio.h>#pragmacomment(lib,"ws2_32.lib")main(){FILE*fp;W...
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
main()
{
FILE * fp;
WSADATA wd;
int retval;
SOCKET sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
struct sockaddr_in saddr;
BOOL bConditionalAccept=TRUE;
struct sockaddr_in saddrsrv;
char heading[3];
char buffer[5000];
int size;
fp=fopen(".\\record.txt","a+");
if((WSAStartup(MAKEWORD(1,1),&wd))==SOCKET_ERROR)
{
printf("Error occured when loading the WINSOCK_DLL...");
exit(-1);
}
WSAStartup(MAKEWORD(2,2),&wd);
saddrsrv.sin_family=AF_INET;
saddrsrv.sin_addr.s_addr=INADDR_BROADCAST;
saddrsrv.sin_port=htons(5050);
setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char FAR *)&bConditionalAccept,sizeof(BOOL));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(5050);
saddr.sin_addr.S_un.S_addr=0;
bind(sock,(struct sockaddr *)&saddr,sizeof(saddr));
size=sizeof(saddrsrv);
for(;;)
{
retval=recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr *)&saddrsrv,&size);
if(retval==SOCKET_ERROR)
{
continue;
}
fprintf(fp,"%s",buffer);
printf("%s",buffer);
}
} 展开
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
main()
{
FILE * fp;
WSADATA wd;
int retval;
SOCKET sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
struct sockaddr_in saddr;
BOOL bConditionalAccept=TRUE;
struct sockaddr_in saddrsrv;
char heading[3];
char buffer[5000];
int size;
fp=fopen(".\\record.txt","a+");
if((WSAStartup(MAKEWORD(1,1),&wd))==SOCKET_ERROR)
{
printf("Error occured when loading the WINSOCK_DLL...");
exit(-1);
}
WSAStartup(MAKEWORD(2,2),&wd);
saddrsrv.sin_family=AF_INET;
saddrsrv.sin_addr.s_addr=INADDR_BROADCAST;
saddrsrv.sin_port=htons(5050);
setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char FAR *)&bConditionalAccept,sizeof(BOOL));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(5050);
saddr.sin_addr.S_un.S_addr=0;
bind(sock,(struct sockaddr *)&saddr,sizeof(saddr));
size=sizeof(saddrsrv);
for(;;)
{
retval=recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr *)&saddrsrv,&size);
if(retval==SOCKET_ERROR)
{
continue;
}
fprintf(fp,"%s",buffer);
printf("%s",buffer);
}
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询