YYgao
YYgao
采纳率0%
2015-10-30 02:36

UDP为什么只能接受指定端口的数据

WORD wVersionRequested = MAKEWORD(2, 2);

WSADATA wsaData;

if(0 != WSAStartup(wVersionRequested, &wsaData))

{

printf("WSAStartup failed with error: %d/n", GetLastError());

return EXIT_FAILURE;

}

if(2 != HIBYTE(wsaData.wVersion) || 2 != LOBYTE(wsaData.wVersion))

{

printf("Socket version not supported./n");

WSACleanup();

return EXIT_FAILURE;

}

g_UdpRecSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

if(INVALID_SOCKET == g_UdpRecSock)

{

printf("socket failed with error: %d/n", WSAGetLastError());

WSACleanup();

return EXIT_FAILURE;

}

SOCKADDR_IN addr;

memset(&addr, 0, sizeof(addr));

addr.sin_family = AF_INET;

addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

addr.sin_port = htonl(INADDR_ANY);//tons(atoi("13400"));//htonl(INADDR_BROADCAST);

if(SOCKET_ERROR == bind(g_UdpRecSock, (LPSOCKADDR)&addr, sizeof(addr)))

{

int i = WSAGetLastError();
printf("bind failed with error: %d/n", WSAGetLastError());

if(INVALID_SOCKET != g_UdpRecSock)

{

closesocket(g_UdpRecSock);

g_UdpRecSock = INVALID_SOCKET;

}

WSACleanup();

return EXIT_FAILURE;

}

char szBuf[MAX_BUFFER] = {0};

SOCKADDR_IN remote;

memset(&remote, 0, sizeof(remote));

int len = sizeof(remote);
char strTemp[1024] = {0};

while(TRUE)  
{  
    if(SOCKET_ERROR == recvfrom(g_UdpRecSock, szBuf, MAX_BUFFER, 0, (LPSOCKADDR)&remote, &len))  
    {  
        int i = WSAGetLastError();
        strerrorid.Format("udp Recv error ID:%d",i);
        m_UdpRecThread->m_listbox.AddString(strerrorid);
        printf("recvfrom failed with error: %d/n", WSAGetLastError());  
    //  ExitThread(0);
        break;  
    } 

    AscToHex(strTemp,(unsigned char *)szBuf, sizeof(szBuf));
    m_UdpDebug.Format("Recv->%s",strTemp);
    m_UdpRecThread->m_listbox.AddString(m_UdpDebug);
}  

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • YYgao YYgao 5年前

    你不指定一个端口,就不知道从哪个端口去获取数据

    点赞 评论 复制链接分享
  • tongyi55555 JonsonJiao 6年前

    这个就是这么规定的,api这么实现的,你可以自己实现多个端口的。

    点赞 评论 复制链接分享
  • zuishikonghuan zuishikonghuan 6年前

    这是UDP协议规定的

    点赞 评论 复制链接分享

相关推荐