UDP socket programming in windows
I developed code to receive udp packets from the port. But after calling recvfrom() nothing is happening. Following is my code and output.
#include "udpSocket.h"
int main(void)
{
SOCKET sockID;
WSADATA wsaData = {0};
FILE *udp;
char buf[512];
static int recvData;
int iResult = 0;
int sock_len = sizeof(fepAddr);
int recvResult;
int seqNo = 0;
static int outOfSeqCnt = 0;
FILE *fp = fopen("outOfSeq.txt","a");
if((udp = fopen("udpData.txt","w")) == 0)
printf("udpData.txt not opened\n");
printf("\n-------------------------------------\n");
printf("\tUDP Packet Receiver\n");
printf("-------------------------------------\n");
printf("\n Enter Destination FEP IP Address : ");
scanf_s("%s",inputData.destIPAddr,16);
printf("\n Enter Destination port from which to receive data : ");
scanf_s("%d",&inputData.portNo,5);
printf("\n Enter No.of iterations : ");
scanf_s("%d",&inputData.noIteration,2);
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(iResult < 0)
{
pri开发者_如何学Cntf("windows socket startup error\n");
}
sockID = socket(PF_INET, SOCK_DGRAM, 0);
if(sockID < 0)
{
printf("Socket creation error\n");
WSACleanup();
}
else
{
printf("Socket Created\n");
}
fepAddr.sin_family = AF_INET;
fepAddr.sin_port = htons(inputData.portNo);
//fepAddr.sin_addr.s_addr = inet_addr(inputData.destIPAddr);
fepAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockID, (struct sockaddr *)&fepAddr, sizeof(struct sockaddr)) < 0)
{
printf("bind() failed: %ld.\n", WSAGetLastError());
closesocket(sockID);
return 0;
}
else
{
printf("bind() is OK!\n");
}
memset(udpBuf, 0, sizeof(udpBuf));
recvData = 1;
while (recvData)
{
printf("receiving data\n");
recvResult = recvfrom(sockID, udpBuf, sizeof(udpBuf), 0,(struct sockaddr *)&fepAddr, &sock_len);
if (recvResult <= 0) {
printf("Socket receive()-error\n");
goto exit;
}
else
printf("Sock success\n");
printf("completed rx data\n");
//puts(udpBuf);
fprintf(udp, "%s", udpBuf);
//fwrite(udpBuf, sizeof(udpBuf), 1, udp);
}
inputData.noIteration--;
if (inputData.noIteration <= 0)*/
recvData-- ;
}
exit:
if(udp)
{
fclose(udp);
udp = 0;
}
//shutdown socket
closesocket(sockID);
fclose(udp);
return 0;
}
- output::::
UDP Packet Receiver
Enter Destination FEP IP Address : 192.168.13.25
Enter Destination port from which to receive data : 2013
Enter No.of iterations : 0 Socket Created bind() is OK! receiving data
Well, first off your bind
call should use sizeof(fepAddr)
(which I assume is struct sockaddr_in
) instead of sizeof(struct sockaddr)
to give it a chance of actually binding to the correct address.
Second, are you sure that someone is actually sending you data? otherwise recvfrom
will block by default.
精彩评论