socket连接总是成功的

时间:2013-07-16 07:33:59

标签: c sockets winapi

我是winsock编程的初学者,我目睹了 connect 函数的特殊行为来建立套接字连接。即使网络中没有有效的主机,套接字功能也会成功。例如,没有主机在我们的网络中使用ip 192.168.4.28 ,但是与呼叫的连接仍然成功,我尝试提供我们网络外的IP地址,例如 1.1.1.1 ,它仍然成功。是否有原因或者api.i中有错误使用了msdn网站中提供的代码  http://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx

CODE

  #ifndef UNICODE
  #define UNICODE
  #endif

  #define WIN32_LEAN_AND_MEAN

  #include <winsock2.h>
  #include <ws2tcpip.h>
  #include <stdio.h>


  #pragma comment(lib, "ws2_32.lib")



  int main()
  {
     WSADATA wsaData;
     int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
     if (iResult != NO_ERROR) {
      wprintf(L"WSAStartup function failed with error: %d\n", iResult);
      return 1;
     }
     SOCKET ConnectSocket;
     ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

     if (ConnectSocket == INVALID_SOCKET) {
     wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
     WSACleanup();
     return 1;
    }
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;

    clientService.sin_addr.s_addr = inet_addr("192.168.4.28"); //No Host by this ip   address 

    clientService.sin_port = htons(80); //Port is 80 

    iResult = connect(ConnectSocket, (SOCKADDR *) & clientService, sizeof      (clientService));

printf("The socket connect return status : %d ",iResult); // always 0 , indicating success

    if (iResult == SOCKET_ERROR) {

    wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());

    iResult = closesocket(ConnectSocket);
    if (iResult == SOCKET_ERROR)
        wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
    WSACleanup();
    return 1;
   }

   wprintf(L"Connected to server.\n");

   iResult = closesocket(ConnectSocket);
   if (iResult == SOCKET_ERROR) {
      printf("\n socket Connection failed ");
      WSACleanup();
      return 1;
   }

   WSACleanup();
   return 0;
 }

0 个答案:

没有答案