开发者

Udp server sending only 0 bytes of data

This is a simple Udp server.I am trying to transmit data to some clients,but unfortunetly it is unable to transmit data.Though send is running quite successfully but it is returning with a return value meaning it has send nothing.On the client they are receiving but again obviously,zero bytes.

   void* UdpServerStreamToClients(void *fileToServe)
   {

    int sockfd,n=0,k;
struct sockaddr_in servaddr,cliaddr;
socklen_t len;
char dataToSend[1000];

sockfd=socket(AF_INET,SOCK_DGRAM,0);

bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(32000);
bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));


FILE *fp;
if((fp=fopen((char*)fileToServe,"r"))==NULL)
    {
        printf("can not open file ");
        perror("fopen");
        exit(1);
    }


int dataRead=1;
while(dataRead)
{

    len = sizeof(cliaddr);
    if((dataRead=fread(dataToS开发者_运维技巧end,1,500,fp))<0)
    {
        perror("fread");
        exit(1);
    }

    //sleep(2);




    for(list<clientInfo>::iterator it=clients.begin();it!=clients.end();it++)
    {
        cliaddr.sin_family = AF_INET;
        inet_aton(inet_ntoa(it->addr.sin_addr),&cliaddr.sin_addr);
        cliaddr.sin_port = htons(it->udp_port);
        n=sendto(sockfd,dataToSend,sizeof(dataToSend),0,(struct sockaddr *)&cliaddr,len);
        cout<<"number of bytes send by udp: "<< n << endl;  
            printf("SEND this message %d : %s to %s :%d \n",n,dataToSend,inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
    }           



}

}

I am checking the value of sizeof(dataTosend) and it is pretty much as expected ie thousand ie the size of buffer. Are you people seeing some possible flaw in it. All of the help in this regard will be appreciated. Thanks!


Not sure this is the exact answer, but you forgot to memset() (or bzero()) the cliaddr structure before using it.

Also, the line:

inet_aton(inet_ntoa(it->addr.sin_addr),&cliaddr.sin_addr);

Could probably be written:

cliaddr.sin_addr = it->addr.sin_addr;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜