std::unique_ptr<UdpSocket> UdpSocket::NewUdpClient(const std::string& host, int port, std::string* error) { if (!InitWinsock()) { if (error) { *error = android::base::StringPrintf("Failed to initialize Winsock (error %d)", WSAGetLastError()); } return nullptr; } SOCKET sock = socket_network_client(host, port, SOCK_DGRAM); if (sock == INVALID_SOCKET) { if (error) { *error = android::base::StringPrintf("Failed to connect to %s:%d (error %d)", host.c_str(), port, WSAGetLastError()); } return nullptr; } return std::unique_ptr<UdpSocket>(new WindowsUdpSocket(sock, WindowsUdpSocket::Type::kClient)); }
int main (int argc, char **argv) { int s; #ifdef WIN32 int err; if ((err = InitWinsock()) != 0) { printf("InitWinsock: Unable to initialize winsock 1.1 (%u)\n", err); return 1; } #endif if ((argc < 3) || (argc > 4)) { printf("Usage: failover <port> <mainip> [failoverip]\n"); return 1; } // connect to the mainip's port if ((s = opentcp(argv[2], atoi(argv[1]), 10)) == -1) { // connection failed, return the error or failoverip if (argc == 3) printf("%s\n", strserr()); else printf("%s\n", argv[3]); } else { closetcp(s); // connection succeeded, return the mainip printf("%s\n", argv[2]); } return 0; }
// Init Live Tracker services, if available void LiveTrackerInit() { if (LiveTrackerInterval == 0) { // If livetracker is not enabled at startup, we do nothing, // but in this case LK must be restarted, if user enables it! StartupStore(TEXT(". LiveTracker disabled.%s"), NEWLINE); return; } //Init winsock if available if (InitWinsock()) { _ws_inited = true; _hNewDataEvent = CreateEvent(NULL, TRUE, FALSE, TEXT("livetrknewdata")); // Create a thread for sending data to the server if ((_hThread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)&LiveTrackerThread, 0, 0, &_dwThreadID)) != NULL) { SetThreadPriority(_hThread, THREAD_PRIORITY_NORMAL); unicode2ascii(LiveTrackersrv_Config, _server_name, SERVERNAME_MAX); _server_name[SERVERNAME_MAX-1]=0; StartupStore(TEXT(". LiveTracker will use server %s if available.%s"), LiveTrackersrv_Config, NEWLINE); _inited = true; } } if (!_inited) StartupStore(TEXT(". LiveTracker init failed.%s"),NEWLINE); }
int main() { InitWinsock(); char szDestIp[] = "172.20.250.21"; SOCKET sRaw = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (sRaw == INVALID_SOCKET) { printf("Create raw socket failed: %d\n", GetLastError()); return -1; } SetTimeout(sRaw, 1000, TRUE); // This function not found on Win API // Set destination SOCKADDR_IN dest; dest.sin_family = AF_INET; dest.sin_port = htons(0); dest.sin_addr.S_un.S_addr = inet_addr(szDestIp); // Create ICMP char buff[sizeof(ICMP_HDR) + 32]; // ICMP_HDR + IPHeader PICMP_HDR pIcmp = (PICMP_HDR) buff; pIcmp->icmp_type = 8; // Echo pIcmp->icmp_code = 0; pIcmp->icmp_id = (USHORT) GetCurrentProcessId(); pIcmp->icmp_checksum = 0; pIcmp->icmp_sequence = 0; memset(&buff[sizeof(ICMP_HDR)], 'E', 32); // filled with whatever // Send / Recv USHORT nSeq = 0; char recvBuf[1024]; SOCKADDR_IN from; int nLen = sizeof(from); while (TRUE) { static int nCount = 0; int nRet = 0; if (nCount ++ == 4) break; pIcmp->icmp_checksum = 0; pIcmp->icmp_timestamp = GetTickCount(); pIcmp->icmp_sequence = nSeq ++; pIcmp->icmp_checksum = checksum((USHORT *) buff, sizeof(ICMP_HDR) + 32); // Send nRet = sendto(sRaw, buff, sizeof(ICMP_HDR) + 32, 0, (SOCKADDR *) &dest, sizeof(dest)); if (nRet == SOCKET_ERROR) { printf("sendto() failed: %d\n", WSAGetLastError()); return -1; } // Recv nRet = recvfrom(sRaw, recvBuf, 1024, 0, (SOCKADDR *) &from, &nLen); if (nRet == SOCKET_ERROR) { if (WSAGetLastError() == WSAETIMEDOUT) { printf("time out\n"); continue; } printf("recvfrom() failed: %d\n", WSAGetLastError()); return -1; } // Unpack int nTick = GetTickCount(); if (nRet < 20 + sizeof(ICMP_HDR)) { printf("Too few bytes from %s\n", inet_ntoa(from.sin_addr)); return -1; } PICMP_HDR pRecvIcmp = (PICMP_HDR)(recvBuf + 20); // size of IP header if (pRecvIcmp->icmp_type != 0) { printf("nonecho type %d received\n", pRecvIcmp->icmp_type); return -1; } if (pRecvIcmp->icmp_id != GetCurrentProcessId()) { printf("someone else's packet!\n"); return -1; } printf(" %d types from %s:", nRet, inet_ntoa(from.sin_addr)); printf(" icmp_seq = %d.", pRecvIcmp->icmp_sequence); printf(" time: %d ms\n", nTick - pRecvIcmp->icmp_timestamp); Sleep(1000); } CleanupWinsock(); return 0; }
// prepares the comm interface for use - MUST be invoked before any data can be sent/received void CCommunicationInterface::PrepareForUse(BOOL bUseNetwork, BOOL bClient) { // clear the network conditions emulation data _pbsSend.Clear(); _pbsRecv.Clear(); // if the network is already initialized, shut it down before proceeding if (cm_bNetworkInitialized) { Unprepare(); } // make sure winsock is off (could be on if enumeration was triggered) GameAgent_EnumCancel(); EndWinsock(); if (bUseNetwork) { CPrintF(TRANSV("Initializing TCP/IP...\n")); if (bClient) { CPrintF(TRANSV(" opening as client\n")); } else { CPrintF(TRANSV(" opening as server\n")); } // make sure winsock is on InitWinsock(); // no address by default cm_ulLocalHost = 0; // if there is a desired local address if (net_strLocalHost!="") { CPrintF(TRANSV(" user forced local address: %s\n"), (const char*)net_strLocalHost); // use that address cm_strName = net_strLocalHost; cm_ulLocalHost = StringToAddress(cm_strName); // if invalid if (cm_ulLocalHost==0 || cm_ulLocalHost==-1) { cm_ulLocalHost=0; // report it CPrintF(TRANSV(" requested local address is invalid\n")); } } // if no valid desired local address CPrintF(TRANSV(" getting local addresses\n")); // get default char hostname[256]; gethostname(hostname, sizeof(hostname)-1); cm_strName = hostname; // lookup the host HOSTENT *phe = gethostbyname(cm_strName); // if succeeded if (phe!=NULL) { // get the addresses cm_strAddress = ""; for(INDEX i=0; phe->h_addr_list[i]!=NULL; i++) { if (i>0) { cm_strAddress += ", "; } cm_strAddress += inet_ntoa(*(const in_addr *)phe->h_addr_list[i]); } } CPrintF(TRANSV(" local addresses: %s (%s)\n"), (const char *) cm_strName, (const char *) cm_strAddress); CPrintF(TRANSV(" port: %d\n"), net_iPort); // try to open master UDP socket try { OpenSocket_t(cm_ulLocalHost, bClient?0:net_iPort); cci_pbMasterInput.pb_ppbsStats = NULL; cci_pbMasterOutput.pb_ppbsStats = NULL; cm_ciBroadcast.SetLocal(NULL); CPrintF(TRANSV(" opened socket: \n")); } catch (char *strError) { CPrintF(TRANSV(" cannot open UDP socket: %s\n"), strError); } } cm_bNetworkInitialized = cci_bWinSockOpen; };
void FTPCore::run() { ClientThread *clientthread; QList<ClientThread*> connections; if (!InitWinsock()) { emit onerror("WinSock init failed"); qDebug() << "Winsock stopped"; emit onstopped(); return; } if ( INVALID_SOCKET == (msocket=socket(AF_INET,SOCK_STREAM,0))) { emit onerror("Error socket " + QString("%1").arg(WSAGetLastError())); WSACleanup(); qDebug() << "Winsock stopped"; emit onstopped(); return; } sockaddr_in local_addr; local_addr.sin_family=AF_INET; local_addr.sin_port=htons(CONTROL_PORT); local_addr.sin_addr.s_addr=0; // вызываем bind для связывания if (SOCKET_ERROR == bind(msocket,(sockaddr *) &local_addr, sizeof(local_addr))) { emit onerror("Error bind " + QString("%1").arg(WSAGetLastError())); closesocket(msocket); WSACleanup(); qDebug() << "Winsock stopped"; emit onstopped(); return; } if (listen(msocket, MAX_CLIENTS)) { // Ошибка emit onerror("Error listen " + QString("%1").arg(WSAGetLastError())); closesocket(msocket); WSACleanup(); emit onstopped(); qDebug() << "Winsock stopped"; return; } SOCKET client_socket; // сокет для клиента sockaddr_in client_addr; // адрес клиента int client_addr_size=sizeof(client_addr); u_long flag = 1; ioctlsocket(msocket, FIONBIO, &flag); fd_set read_s; // Множество timeval time_out; // Таймаут int res; emit onstarted(); while (true) { FD_ZERO (&read_s); // Обнуляем множество FD_SET (msocket, &read_s); // Заносим в него наш сокет time_out.tv_sec = 0; time_out.tv_usec = 500000; //Таймаут 0.5 секунды. if (SOCKET_ERROR == (res = select (0, &read_s, NULL, NULL, &time_out) ) ) { emit onerror("Select error in FTPCore"); closesocket(msocket); WSACleanup(); qDebug() << "Winsock stopped"; emit onstopped(); return; } if ((res!=0) && (FD_ISSET (msocket, &read_s)) ) // Использую FD_ISSET только для примера! :) { client_socket=accept(msocket, (sockaddr *)&client_addr, &client_addr_size); QString clientAddr = QString("%1:%2").arg(inet_ntoa(client_addr.sin_addr)).arg(client_addr.sin_port); emit onnewconnection(clientAddr); clientthread = new ClientThread(client_socket, clientAddr); connections.append(clientthread); connect(clientthread, SIGNAL(oncloseconnection(QString)),SIGNAL(oncloseconnection(QString))); clientthread->start(); } if (terminated) { break; } } foreach(ClientThread *client , connections) { client->closeconnection(); qDebug() << "Close connection"; client->wait(); qDebug() << "wait"; delete client; }