2016-04-11 355 views
0

我對WSAGetLastError()提供了10038的bind()和sendto()方法存在問題,MSDN在套接字上表示爲無效操作。我不明白我的代碼有什麼問題。我已經在TCP上測試了我的代碼,它正在工作,但在UDP上無法正常工作。我已經看到其他人發生過相同錯誤的帖子,但是它主要是套接字關閉的問題。 在此先感謝。給出錯誤10038(WSAENOTSOCK)的綁定方法

int socket_func :: udpRelayCheck() 
    { 
     WSADATA __wsaData; 
     WORD __version = WSAStartup(MAKEWORD(2, 2), &__wsaData); 

     if (__version != 0) 
     { 
     WSACleanup(); 
     return 1; 
     } 

     SOCKET  __ping_server_socket; 
     sockaddr_in __ping_server_service; 

     if (__ping_server_socket = socket(AF_INET, SOCK_DGRAM, 0) == SOCKET_ERROR) 
     { 
     WSACleanup(); 
     return 2; 
     } 

     memset((void*)&__ping_server_service, 0, sizeof(__ping_server_service)); 

     __ping_server_service.sin_family = AF_INET; 
     __ping_server_service.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); 
     __ping_server_service.sin_port = htons(55555); 

     int __ping_server_service_length = sizeof(__ping_server_service); 

     char *__relayMessage = "connect"; 
     char __recvBuff[200] = ""; 
     char *__check_buffer = "star"; 

     if (bind(__ping_server_socket, (struct sockaddr *)&__ping_server_service, sizeof(__ping_server_service)) == INVALID_SOCKET) 
     { 
      cout << WSAGetLastError() << endl; 
      return -1; 
     } 
     while (1) 
     { 
      if (sendto(__ping_server_socket, __relayMessage,strlen(__relayMessage), 0, (struct sockaddr *)&__ping_server_service, __ping_server_service_length) == SOCKET_ERROR) 
     { 
      cout << WSAGetLastError() << endl; 
      return -1; 
     } 

     if (recvfrom(__ping_server_socket, __recvBuff, strlen(__recvBuff), 0, (SOCKADDR*)& __ping_server_service, &__ping_server_service_length) != SOCKET_ERROR) 
     { 
      if (strcmp(__check_buffer, __recvBuff) == 0) 
      { 
       __global_udp_relay_socket = __ping_server_socket; 
       __global_udp_relay_sockaddr = __ping_server_service; 

       WSACleanup(); 
       return 0; 
      } 
     } 
    } 
} 
+1

不要將以'__'開頭的變量命名,這是保留給實現的。 – Barmar

+0

這是什麼意思? –

+0

保留以兩個下劃線開頭的變量和函數名稱,您不允許在自己的變量和函數中使用這些名稱,以避免衝突的可能性。 – Barmar

回答

1

這條線的問題是:

if (__ping_server_socket = socket(AF_INET, SOCK_DGRAM, 0) == SOCKET_ERROR) 

它設置__ping_server_socket到比較的結果(truefalse,它轉換到整數10),不被返回的值socket()。您需要在任務周圍使用括號來覆蓋默認的運算符優先級。

if ((__ping_server_socket = socket(AF_INET, SOCK_DGRAM, 0)) == SOCKET_ERROR) 
+0

非常感謝!工作! –

0
if (__ping_server_socket = socket(AF_INET, SOCK_DGRAM, 0) == SOCKET_ERROR) 

優先問題。它應該是:

if ((__ping_server_socket = socket(AF_INET, SOCK_DGRAM, 0)) == SOCKET_ERROR)