套接字连接未连接

时间:2014-07-24 16:25:38

标签: c++ sockets

我不知道我能不能做我想做的事。基本上我想要做的是知道何时有以太网连接以及何时没有它。我有这个代码,它基本上是IP的套接字:

void* RecvTP(void*)
{
    struct sockaddr_in remoteSocketInfo;
    struct hostent *hPtr;
    int socketHandle;
    const char *remoteHost="192.168.1.70";
    int portNumber = 65000;
    char *pcIpAddress;
    unsigned short shPort;

    bzero(&remoteSocketInfo, sizeof(sockaddr_in));  // Clear structure memory

    // Get system information

    if((hPtr = gethostbyname(remoteHost)) == NULL)
    {
        cout << "System DNS name resolution not configured properly." << endl;
        cerr << "Error number: " << ECONNREFUSED << endl;
        exit(EXIT_FAILURE);
    }

    // create socket

    if((socketHandle = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {

       cout<<"error1"<<endl;
       close(socketHandle);
       exit(EXIT_FAILURE);
    }

    // Load system information into socket data structures

    memcpy((char *)&remoteSocketInfo.sin_addr, hPtr->h_addr, hPtr->h_length);
    remoteSocketInfo.sin_family = AF_INET;
    remoteSocketInfo.sin_port = htons((u_short)portNumber);      // Set port number



    int rc = 0;  // Actual number of bytes read by function read()
    char buf[4];


  while(1){

      if(connect(socketHandle, (struct sockaddr *)&remoteSocketInfo, sizeof(sockaddr_in)) < 0)
 {
      cout<<"error2"<<endl;
    //  close(socketHandle);
     // exit(EXIT_FAILURE);
 }
 if(connect(socketHandle, (struct sockaddr *)&remoteSocketInfo, sizeof(sockaddr_in)) >= 0)
 {
     cout<<"NO error"<<endl;
    // close(socketHandle);
         // exit(EXIT_FAILURE);
 }

   rc = recv(socketHandle, buf, 4, 0);

/*   if ( rc == 0 || rc == -1)
   {
       cerr << "ERROR! Socket closed" << endl;
   }

   else if (rc == -1)
   {
       cerr << "ERROR! Socket error" << endl;
       close(socketHandle);
   }*/

    if(buf[2]=='3')
        recievePhoneState=0x01;
    else
       if(buf[2]=='0')
        recievePhoneState=0x02;

}

}

我想知道的是,如果我可以控制,当我有连接时,我不知道。 我正在尝试使用函数connect,但它不起作用,有一些套接字函数或者我可以知道我是否有连接以及什么时候我不知道?

有人有想法吗?

0 个答案:

没有答案