📄 connectivity_core_utils.cpp
字号:
/*
Copyright (c) 2008, Intel Corporation.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*///==============================================================================// Connectivity_core_utils.cpp//// Provide the intelnal used global method to support the APIs in connectivity//// //==============================================================================/*#include "stdafx.h"#include <winsock2.h>#include <ws2tcpip.h>#include <wininet.h>*/#include <list>#include <time.h>#include <algorithm>#include <net/if.h>#include <net/if_arp.h>#include <netinet/in.h>#include <sys/socket.h>#include <fcntl.h>#include "Instance_Connectivity.h"#include "Connectivity_core_utils.h"#include "qtime.h"#include <sys/ioctl.h>#include "inc/framework/base_Exception.h"#include "inc/network/network_LinkProtocolClassObject.h"#include "inc/network/network_LinkProtocolInstanceObject.h"#include <vector>#include <sys/types.h>#include <netdb.h>//#include <openssl/crypto.h>#include <openssl/ssl.h>#include <openssl/err.h>#include <openssl/rand.h>#define LIBHTTP_VERSION "0.9" //for httpusing namespace std;/* ________________________________________________________________global________________________________________________________________ *///#define WSADESCRIPTION_LEN 256#define WSASYS_STATUS_LEN 256#define SOCKET_ERROR (-1)#define INVALID_SOCKET (-1)int SAGetLastError(){ // for temp perror("SAGetLastError"); return 0;}typedef char* LPCWSTR;typedef LPVOID HINTERNET;#define MAXTIMEOUT 60000typedef struct { LPCWSTR pHost; LPCWSTR pUser; LPCWSTR pPass; } PARM;HINTERNET g_hOpen, g_hConnect, g_hRequest;//////////////////////////////////////////////////////////////////////////WinAPI///////////////////////////////////////////////////////////////////////typedef struct WSAData { WORD wVersion; WORD wHighVersion;#ifdef _WIN64 unsigned short iMaxSockets; unsigned short iMaxUdpDg; char FAR * lpVendorInfo; char szDescription[WSADESCRIPTION_LEN+1]; char szSystemStatus[WSASYS_STATUS_LEN+1];#else char szDescription[WSADESCRIPTION_LEN+1]; char szSystemStatus[WSASYS_STATUS_LEN+1]; unsigned short iMaxSockets; unsigned short iMaxUdpDg; char FAR * lpVendorInfo;#endif} WSADATA;typedef struct sockaddr SOCKADDR;typedef struct _SOCKET_INFO{ SOCKET sock; sockaddr_in saAddr;} SOCKET_INFO;typedef enum{ PONG_COMPLETE, PONG_HOP, PONG_FAILURE, PONG_RETRY} PONG_STATUS;// Packet types#define cICMP_REPLY 0#define cICMP_ECHO 8#define cICMP_TIME_EXCEEDED 11// Packet codes#define cTTL_EXCEEDED 0#pragma pack(1)//IP headertypedef struct{ BYTE h_len:4; // length of the header BYTE version:4; // Version of IP BYTE tos; // Type of service USHORT total_len; // total length of the packet USHORT ident; // unique identifier USHORT frag_and_flags; // flags BYTE ttl; BYTE proto; // protocol (TCP, UDP etc) USHORT checksum; // IP checksum UINT sourceIP; UINT destIP;} IP_HEADER;typedef struct _SOCK_TIME{ sockaddr_in SockAddr; DWORD StartTime; DWORD StopTime;} SOCK_TIME;// icmp headertypedef struct _ICMP_HEADER{ BYTE i_type; BYTE i_code; // type sub code USHORT i_cksum; USHORT i_id; USHORT i_seq; ULONG timestamp;} ICMP_HEADER;#pragma pack()#define MAX_IP_Q 3#define HTTPPORT 80#define HTTPSPORT 443#define FTPPORT 21#define MAX_Q 64USHORT s_nPacketSeq = 1;USHORT s_nAppId = 0;vector<SOCK_TIME> *g_paHops[32];int g_Head = 0; int g_Tail = 0; CQTime g_cQTime;DWORD g_StartTime;DWORD g_StopTime;const int nPACKET_SIZE = 1024; // needs to be larger for some hardware for some reason?bool g_bWSAStarted = false; // winsock started/* ______________________________________________________________ Get the IPAdress of the input networkadaptor ______________________________________________________________ */bool getIpofNetworkAdptor(sockaddr_in* sAddress, IntelMobileString& pNetworkAdaptorKey){ //USES_CONVERSION; unsigned int IPAddr; IntelMobileString mIipaddr; hostent* pHostIP; ServerInstanceObject *ppLinkProtocolInstance = ( GetLayer()->GetLayerClassObject(IntelMobileText("LinkProtocol")) ).GetInstance(pNetworkAdaptorKey); if (ppLinkProtocolInstance == NULL) return false; ServerLinkProtocolInstanceObject* pLinkProtocolInstance = dynamic_cast<ServerLinkProtocolInstanceObject*>( ppLinkProtocolInstance ); if(!pLinkProtocolInstance->IpAddress.IsNull()) { mIipaddr = pLinkProtocolInstance->IpAddress.GetValue(); IPAddr = inet_addr(mIipaddr.c_str()); //printf("may has but in T2A\n"); pHostIP = gethostbyaddr((char *)&IPAddr, sizeof(IPAddr), AF_INET); if( NULL == pHostIP ) { herror("gethostbyaddr"); return false; } memcpy((void*)&sAddress->sin_addr,(void*)pHostIP->h_addr, pHostIP->h_length); sAddress->sin_family = pHostIP->h_addrtype; sAddress->sin_port = 0; memset(&(sAddress->sin_zero), 0, 8); return true; } else { return false; } }intconnect_nonb(int sockfd, const struct sockaddr *saptr, socklen_t salen, int nsec){ int flags, n, error; socklen_t len; fd_set rset, wset; struct timeval tval; flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); error = 0; if ( (n = connect(sockfd, saptr, salen)) < 0){ perror("connect"); if (errno != EINPROGRESS) return (-1); return -1;} // Do whatever we want while the connect is taking place. if (n == 0) goto done; // connect completed immediately FD_ZERO(&rset); FD_SET(sockfd, &rset); wset = rset; tval.tv_sec = nsec; tval.tv_usec = 0; if ( (n = select(sockfd + 1, &rset, &wset, NULL, nsec ? &tval : NULL)) == 0) { close(sockfd); // timeout errno = ETIMEDOUT; return (-1); } if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) { len = sizeof(error); if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) return (-1); // Solaris pending error } else printf("select error: sockfd not set\n"); done: fcntl(sockfd, F_SETFL, flags); // restore file status flags if (error) { close(sockfd); // just in case errno = error; return (-1); } return (0);}/*///---------///---------The following methods: StartNetwork and socketClient is used to initialize //////---------and set up the socket connection for the local host system /// ///---------------------------------------------------------------------------------------------------------///*//* ______________________________________________________________ StartNetwork ______________________________________________________________ */#define MAXINTERFACES 16bool StartNetwork(){ try { struct ifreq buf[MAXINTERFACES]; struct ifconf ifc; int fd,interface=0; char command[32]=""; bool bRet=false; if((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) { ifc.ifc_len=sizeof buf; ifc.ifc_buf=(caddr_t)buf; if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) { interface = ifc.ifc_len / sizeof (struct ifreq); while (interface-- > 0) { //may has bug , because there are more than one network card if (!ioctl (fd, SIOCGIFFLAGS, &buf[interface])) { if(0xf0&buf[interface].ifr_flags & IFF_UP)//if(0xf0&ifr.ifr_flags&IFF_RUNNING) bRet = true; else { sprintf(command, "ifup %s", buf[interface]); system(command); printf("%s\n", command); bRet = true; } } else bRet = false; } } } return bRet; } catch(...) { THROWIMEXCEPTION("8004320E"); } return true;}/* ________________________________________________________________SocketClient ________________________________________________________________ */SOCKET socketClient(struct hostent *hp, int port, unsigned long ulSelectedIP=0){ try { const int ON = 1; const int OFF = -1; const int nRcvTimeOut = 3000; SOCKET s; struct sockaddr_in sa; if (hp == NULL) { printf("hp == null\n"); return -1; } // fill the sa struct used by connect memcpy((void*)&sa.sin_addr, (void*)hp->h_addr, hp->h_length); sa.sin_family = hp->h_addrtype; sa.sin_port = htons(port); memset(&(sa.sin_zero), 0, 8); if ((s = socket(hp->h_addrtype, SOCK_STREAM, IPPROTO_TCP)) < 0) return -1; printf("sockid is %d\n", s); // if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&ON, sizeof(int)) < 0) // set receive timeout to 3000ms struct timeval tv = { nRcvTimeOut/1000, nRcvTimeOut%1000 }; //if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO ,(char *)&nRcvTimeOut, sizeof(int)) == 0) if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO ,&tv, sizeof(tv)) == 0) { sockaddr_in sa1; char MachineName[255]; DWORD Size=254; addrinfo *pAddrInfo; addrinfo AddrInfo; gethostname(MachineName, Size); printf("hostname %s\n", MachineName); memset(&AddrInfo, 0, sizeof(addrinfo)); int nRet = getaddrinfo(MachineName, NULL, &AddrInfo, &pAddrInfo); printf(" %s nRet=%d %s\n", MachineName, nRet, htonl(AddrInfo.ai_addr)); if ( !nRet ) { memcpy(&sa1, pAddrInfo->ai_addr, sizeof(sockaddr_in)); sa1.sin_family = AF_INET; sa1.sin_addr.s_addr = ulSelectedIP; } else { printf("nRet %d\n", nRet); perror("getaddrinfo"); } if ( bind(s, (SOCKADDR*)&sa1, sizeof(sa1)) == SOCKET_ERROR ) { perror("bind"); close(s); return -1; } // call connect if (connect(s,(struct sockaddr *)(&sa),sizeof(struct sockaddr)) < 0) // if(connect_nonb(s, (struct sockaddr *)&sa, sizeof(struct sockaddr), 3000 )!=0) { perror("connect"); close(s); return -1; } else { printf("socketClient %d\n", s); return s; } } else { close(s); perror("setsockopt"); return -1; } } catch(...) { THROWIMEXCEPTION("8004320F"); }}SOCKET socketClientEx(struct hostent *hp, int port, unsigned int *pTimeOut, unsigned int *pRetryCount, IntelMobileString& pNetworkAdaptorKey, unsigned long ulSelectedIP=0){ try { const int ON = 1; const int OFF = -1; SOCKET s; if(*pTimeOut == 0) *pTimeOut = MAXTIMEOUT; //printf("time %d\n", *pTimeOut); timeval tv = { (long)(*pTimeOut)/1000,(long)(*pTimeOut)%1000 }; struct sockaddr_in sa; if (hp == NULL) { printf(" bug host==NULL\n"); return -1; } // fill the sa struct used by connect else { memcpy((void*)&sa.sin_addr, (void*)hp->h_addr, hp->h_length); sa.sin_family = hp->h_addrtype; sa.sin_port = htons(port); } memset(&(sa.sin_zero), 0, 8); if ((s = socket(hp->h_addrtype, SOCK_STREAM, IPPROTO_TCP)) < 0) return -1; //printf("type %d addr %s port %d %d\n", hp->h_addrtype, inet_ntoa(sa.sin_addr), port, s); sockaddr_in sa1; if(pNetworkAdaptorKey == IntelMobileText("Any")) { char MachineName[255]; DWORD Size=254; addrinfo *pAddrInfo; addrinfo AddrInfo; gethostname(MachineName, Size); memset(&AddrInfo, 0, sizeof(addrinfo)); int nRet = getaddrinfo(MachineName, NULL, &AddrInfo, &pAddrInfo); //printf(" %s nRet=%d %s\n", MachineName, nRet, htonl(AddrInfo.ai_addr)); if ( !nRet )
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -