void Starter::Boot(Message & message) { PrintAddress(); cout << "booting..." << endl; srand(time(NULL) * GetAddress()); finished = 0; NetworkTester::ACTORS_PER_RANK = 4; int count = NetworkTester::ACTORS_PER_RANK; for(int i = 0 ; i < count; ++i) { Actor * actor = new NetworkTester(); Spawn(actor); PrintAddress(); cout << "spawns actor " << actor->GetAddress() << endl; int address = actor->GetAddress(); Message startMessage; startMessage.SetTag(NetworkTester::START); Send(address, startMessage); } }
void Starter::Advise(Message & message) { finished ++; int total = GetSize() * NetworkTester::ACTORS_PER_RANK; PrintAddress(); cout << "finished: " << finished << endl; if(finished == total) { Message death; PrintAddress(); cout << "killing Starter actors" << endl; // also kill Starter actors too. for(int i = 0 ; i < GetSize() ; ++i) { int address = i; death.SetTag(Starter::DIE); Send(address, death); } PrintAddress(); cout << "killing NetworkTester actors" << endl; // kill other actors for(int i = 0; i < total; ++i) { int address = i + GetSize(); death.SetTag(NetworkTester::DIE); Send(address, death); } } }
//------------------------------------------------------------------------- // Print a Bank_t. void PrintBank(const Bank_t *bank) { printf("|%d", bank->oneshotPending); PrintAddress(&bank->current); PrintAddress(&bank->last); }
void count_to_20(int counter) { int i; // Changes every recursion //static int i; // Stays the same if (counter <= 20) { PrintAddress(i); count_to_20(++counter); } }
//------------------------------------------------------------------------- // Print a ParseOutput_t. void PrintOutputRecord(const ParseOutput_t *record) { PrintAddress(&record->ProgramCounter); printf(" "); PrintBank(&record->EBank); printf(" "); PrintBank(&record->SBank); }
static void Server(void) { PRStatus rv; PRNetAddr server_address, client_address; PRFileDesc *xport = PR_Socket(domain, PR_SOCK_STREAM, protocol); if (NULL == xport) { PL_FPrintError(err, "PR_Socket"); return; } rv = PR_InitializeNetAddr(PR_IpAddrAny, PORT_NUMBER, &server_address); if (PR_FAILURE == rv) PL_FPrintError(err, "PR_InitializeNetAddr"); else { rv = PR_Bind(xport, &server_address); if (PR_FAILURE == rv) PL_FPrintError(err, "PR_Bind"); else { PRFileDesc *client; rv = PR_Listen(xport, 10); PR_fprintf(err, "Server listening on "); (void)PrintAddress(&server_address); do { client = PR_Accept( xport, &client_address, PR_INTERVAL_NO_TIMEOUT); if (NULL == client) PL_FPrintError(err, "PR_Accept"); else { PR_fprintf(err, "Server accepting from "); (void)PrintAddress(&client_address); shared->threads += 1; (void)PR_CreateThread( PR_USER_THREAD, Servette, client, PR_PRIORITY_NORMAL, thread_scope, PR_UNJOINABLE_THREAD, 8 * 1024); } } while (PR_TRUE); } } } /* Server */
void NetworkTester::Start(Message & message) { sum = 0; messages = 0; controller = 0; PrintAddress(); cout << "starting !" << endl; int address = GetAddress(); PrintAddress(); cout << "Sending SAY_HELLO message to " << address << endl; Message dummyMessage; dummyMessage.SetTag(SAY_HELLO); Send(address, dummyMessage); }
static void print_address_1 (int32_t reladdr, uint32_t absaddr, int flags, void *stream, void (*fprintf_f) (void *, const char *, ...), void (*fputs_f) (const char *, void *)) { int rcid; const char *rcname; PrintAddress (reladdr, absaddr, flags, stream, fprintf_f, fputs_f); if (((rcid = romcalls_is_addr (absaddr)) != -1) && ((rcname = romcalls_get_name (rcid)) != NULL)) fprintf_f (stream, " /* tios::%s */", rcname); }
void NetworkTester::SayHello(Message & message) { int total = GetSize() * ACTORS_PER_RANK; PrintAddress(); cout << "Hello ! I am " << GetAddress(); cout << " out of " << total << " NetworkTester actors" << endl; Message dummyMessage; dummyMessage.SetTag(TEST_MESSAGE_RESPONSE); int address = GetAddress(); timeBefore = GetMicroSeconds(); Send(address, dummyMessage); }
void Starter::Receive(Message & message) { int tag = message.GetTag(); if(tag == Actor::BOOT) { Boot(message); } else if(tag == DIE) { PrintAddress(); cout << "Now I must die..." << endl; Die(message); } else if(tag == ADVISE) { Advise(message); } }
void AMXStackFramePrinter::PrintArgumentValue(const AMXStackFrame &frame, const AMXDebugSymbol &arg, int index) { std::string tag_name = debug_info_.GetTagName(arg.GetTag()); cell value = GetArgumentValue(frame, index); if (arg.IsVariable()) { PrintValue(tag_name, value); return; } stream_ << "@"; PrintAddress(value); if (arg.IsReference()) { if (cell *ptr = GetDataPtr(frame.amx(), value)) { stream_ << " "; PrintValue(tag_name, *ptr); } return; } if (arg.IsArray() || arg.IsArrayRef()) { std::vector<AMXDebugSymbolDim> dims = arg.GetDims(); // Try to filter out non-printable arrays (e.g. non-strings). // This doesn't work 100% of the time, but it's better than nothing. if (dims.size() == 1 && tag_name == "_" && debug_info_.GetTagName(dims[0].GetTag()) == "_") { std::string string; bool packed; GetStringContents(frame.amx(), value, dims[0].GetSize(), string, packed); stream_ << (packed ? " !" : " "); static const std::size_t kMaxString = 80; if (string.length() > kMaxString) { string.replace(kMaxString, string.length() - kMaxString, "..."); } stream_ << "\"" << string << "\""; } } }
void NetworkTester::TestMessageResponse(Message & message) { uint64_t timeAfter = GetMicroSeconds(); int latency = (timeAfter - timeBefore) / 2; sum += latency; messages ++; int messagesToSend = 10000; if(messages == messagesToSend) { PrintAddress(); cout << "communicated " << messages << " "; cout << " TEST_MESSAGE messages"; int average = sum / messages; cout << " point-to-point latency: "; cout << average << " us" << endl; // kill the actor Message dummyMessage; dummyMessage.SetTag(Starter::ADVISE); int address = controller; Send(address, dummyMessage); } else { // send a message to a random stranger int total = GetSize() * ACTORS_PER_RANK; int address = rand() % total; // skip Starter actors address += GetSize() * 1; Message dummyMessage; dummyMessage.SetTag(TEST_MESSAGE); Send(address, dummyMessage); } }
// // Function: AddReceiveInterface // // Description: // This routine adds the given interface to the receiving interfac // list. This option is valid only for receivers. // int AddReceiveInterface(SOCKET s, struct addrinfo *iface) { int rc; rc = setsockopt( s, IPPROTO_RM, RM_ADD_RECEIVE_IF, (char *)&((SOCKADDR_IN *)iface->ai_addr)->sin_addr.s_addr, sizeof(ULONG) ); if (rc == SOCKET_ERROR) { printf("setsockopt: RM_ADD_RECEIVE_IF failed: %d\n", WSAGetLastError()); } else { printf("Adding receive interface: "); PrintAddress(iface->ai_addr, iface->ai_addrlen); printf("\n"); } return rc; }
// // Function: SetSendInterface // // Description: // This routine sets the sending interface. This option may only be set // on senders. // int SetSendInterface(SOCKET s, struct addrinfo *iface) { int rc; // Set the send interface rc = setsockopt( s, IPPROTO_RM, RM_SET_SEND_IF, (char *)&((SOCKADDR_IN *)iface->ai_addr)->sin_addr.s_addr, sizeof(ULONG) ); if (rc == SOCKET_ERROR) { printf("setsockopt failed: %d\n", WSAGetLastError()); } else { printf("Set sending interface to: "); PrintAddress(iface->ai_addr, iface->ai_addrlen); printf("\n"); } return rc; }
void NetworkTester::Receive(Message & message) { int tag = message.GetTag(); switch(tag) { case TEST_MESSAGE: { TestMessage(message); } break; case TEST_MESSAGE_RESPONSE: { TestMessageResponse(message); } break; case START: { Start(message); } break; case SAY_HELLO: { SayHello(message); } break; case DIE: { PrintAddress(); cout << "Now I die." << endl; Die(message); } break; } }
// // Function: main // // Description: // This function loads Winsock, parses the command line, and // begins receiving packets. Once a packet is received they // are decoded. Because we are receiving IP datagrams, the // receive call will return whole datagrams. // int __cdecl main(int argc, char **argv) { SOCKET s = INVALID_SOCKET; WSADATA wsd; WSABUF wbuf = {0}; DWORD dwBytesRet = 0, dwFlags = 0; char *rcvbuf=NULL; int rc = 0, err; // // Load Winsock // if ((rc = WSAStartup(MAKEWORD(2,2), &wsd)) != 0) { printf("WSAStartup() failed: %d\n", rc); return -1; } // // Parse the command line // if (ValidateArgs(argc, argv) == SOCKET_ERROR) { usage(argv[0]); } if ( g_ulFilterMask & (FILTER_MASK_SOURCE_ADDRESS | FILTER_MASK_SOURCE_PORT) ) { printf("Source address filter : "); PrintAddress((SOCKADDR *)&g_saSourceAddress, sizeof(g_saSourceAddress)); printf("\n"); } if ( g_ulFilterMask & (FILTER_MASK_DESTINATION_ADDRESS | FILTER_MASK_DESTINATION_PORT) ) { printf("Destination address filter: "); PrintAddress((SOCKADDR *)&g_saDestinationAddress, sizeof(g_saDestinationAddress)); printf("\n"); } // // Create a raw socket for receiving IP datagrams // s = WSASocket(g_saLocalInterface.ss_family, SOCK_RAW, g_dwProtocol, NULL, 0, WSA_FLAG_OVERLAPPED); if (s == INVALID_SOCKET) { printf("WSASocket() failed: %d\n", WSAGetLastError()); return -1; } // // This socket MUST be bound before calling the ioctl // rc = bind(s, (SOCKADDR *)&g_saLocalInterface, sizeof(g_saLocalInterface)); if (rc == SOCKET_ERROR) { printf("bind() failed: %d\n", WSAGetLastError()); if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return -1; } printf("Binding to: "); PrintAddress((SOCKADDR *)&g_saLocalInterface, sizeof(g_saLocalInterface)); printf("\n"); // // Set the SIO_RCVALLxxx ioctl // rc = WSAIoctl(s, g_dwIoControlCode, &g_dwIoControlValue, sizeof(g_dwIoControlValue), NULL, 0, &dwBytesRet, NULL, NULL); if (rc == SOCKET_ERROR) { printf("WSAIotcl(0x%x) failed: %d\n", g_dwIoControlCode, (err = WSAGetLastError())); if (err == WSAEINVAL) { printf("NOTE: IPv6 does not currently support the SIO_RCVALL* ioctls\n"); } if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return -1; } // // Allocate a buffer for receiving data // rcvbuf = (char *)HeapAlloc(GetProcessHeap(), 0, MAX_IP_SIZE); if (rcvbuf == NULL) { fprintf(stderr, "HeapAlloc failed: %d\n", GetLastError()); if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return -1; } // // Start receiving IP datagrams until interrupted // while (1) { wbuf.len = MAX_IP_SIZE; wbuf.buf = rcvbuf; dwFlags = 0; rc = WSARecv(s, &wbuf, 1, &dwBytesRet, &dwFlags, NULL, NULL); if (rc == SOCKET_ERROR) { printf("WSARecv() failed: %d\n", WSAGetLastError()); break; } // Decode the IP header // rc = DecodeIPHeader( rcvbuf, dwBytesRet, g_ulFilterMask, (SOCKADDR *)&g_saSourceAddress, (SOCKADDR *)&g_saDestinationAddress ); if (rc != NO_ERROR) { printf("Error decoding IP header!\n"); break; } } // // Cleanup // if (rcvbuf) HeapFree(GetProcessHeap(), 0, rcvbuf); if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return 0; }
// // Function: main // // Description: // This is the main program. It parses the command line and creates // the main socket. For UDP this socket is used to receive datagrams. // For TCP the socket is used to accept incoming client connections. // Each client TCP connection is handed off to a worker thread which // will receive any data on that connection until the connection is // closed. // int __cdecl main(int argc, char **argv) { WSADATA wsd; THREAD_OBJ *thread=NULL; SOCKET_OBJ *sockobj=NULL, *newsock=NULL; int index, rc; struct addrinfo *res=NULL, *ptr=NULL; // Validate the command line ValidateArgs(argc, argv); // Load Winsock if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { fprintf(stderr, "unable to load Winsock!\n"); return -1; } printf("Local address: %s; Port: %s; Family: %d\n", gBindAddr, gBindPort, gAddressFamily); res = ResolveAddress(gBindAddr, gBindPort, gAddressFamily, gSocketType, gProtocol); if (res == NULL) { fprintf(stderr, "ResolveAddress failed to return any addresses!\n"); return -1; } thread = GetThreadObj(); // For each local address returned, create a listening/receiving socket ptr = res; while (ptr) { PrintAddress(ptr->ai_addr, ptr->ai_addrlen); printf("\n"); sockobj = GetSocketObj(INVALID_SOCKET, (gProtocol == IPPROTO_TCP) ? TRUE : FALSE); // create the socket sockobj->s = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (sockobj->s == INVALID_SOCKET) { fprintf(stderr,"socket failed: %d\n", WSAGetLastError()); return -1; } InsertSocketObj(thread, sockobj); // bind the socket to a local address and port rc = bind(sockobj->s, ptr->ai_addr, ptr->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } if (gProtocol == IPPROTO_TCP) { rc = listen(sockobj->s, 200); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen failed: %d\n", WSAGetLastError()); return -1; } // Register events on the socket rc = WSAEventSelect( sockobj->s, sockobj->event, FD_ACCEPT | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEventSelect failed: %d\n", WSAGetLastError()); return -1; } } else { // Register events on the socket rc = WSAEventSelect( sockobj->s, sockobj->event, FD_READ | FD_WRITE | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEventSelect failed: %d\n", WSAGetLastError()); return -1; } } ptr = ptr->ai_next; } // free the addrinfo structure for the 'bind' address freeaddrinfo(res); gStartTime = gStartTimeLast = GetTickCount(); while (1) { rc = WaitForMultipleObjects( thread->SocketCount + 1, thread->Handles, FALSE, 5000 ); if (rc == WAIT_FAILED) { fprintf(stderr, "WaitForMultipleObjects failed: %d\n", GetLastError()); break; } else if (rc == WAIT_TIMEOUT) { PrintStatistics(); } else { index = rc - WAIT_OBJECT_0; sockobj = FindSocketObj(thread, index-1); if (gProtocol == IPPROTO_TCP) { SOCKADDR_STORAGE sa; WSANETWORKEVENTS ne; SOCKET sc; int salen; rc = WSAEnumNetworkEvents( sockobj->s, thread->Handles[index], &ne ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEnumNetworkEvents failed: %d\n", WSAGetLastError()); break; } while (1) { sc = INVALID_SOCKET; salen = sizeof(sa); // // For TCP, accept the connection and hand off the client socket // to a worker thread // sc = accept( sockobj->s, (SOCKADDR *)&sa, &salen ); if ((sc == INVALID_SOCKET) && (WSAGetLastError() != WSAEWOULDBLOCK)) { fprintf(stderr, "accept failed: %d\n", WSAGetLastError()); break; } else if (sc != INVALID_SOCKET) { newsock = GetSocketObj(INVALID_SOCKET, FALSE); // Copy address information memcpy(&newsock->addr, &sa, salen); newsock->addrlen = salen; newsock->s = sc; InterlockedIncrement(&gTotalConnections); InterlockedIncrement(&gCurrentConnections); /* printf("Accepted connection from: "); PrintAddress((SOCKADDR *)&newsock->addr, newsock->addrlen); printf("\n"); */ // Register for read, write and close on the client socket rc = WSAEventSelect( newsock->s, newsock->event, FD_READ | FD_WRITE | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEventSelect failed: %d\n", WSAGetLastError()); break; } AssignToFreeThread(newsock); } else { // Failed with WSAEWOULDBLOCK -- just continue break; } } } else { // For UDP all we have to do is handle events on the main // threads. if (HandleIo(thread, sockobj) == SOCKET_ERROR) { RenumberThreadArray(thread); } } } } WSACleanup(); return 0; }
// // Function: main // // Description: // This is the main program. It parses the command line and creates // the main socket. For UDP this socket is used to receive datagrams. // For TCP the socket is used to accept incoming client connections. // Each client TCP connection is handed off to a worker thread which // will receive any data on that connection until the connection is // closed. // int __cdecl main(int argc, char **argv) { WSADATA wsd; SOCKET_OBJ *sockobj=NULL, *sptr=NULL, *tmp=NULL; HANDLE hThread; ULONG lastprint=0; MSG msg; int rc; struct addrinfo *res=NULL, *ptr=NULL; ValidateArgs(argc, argv); InitializeCriticalSection(&gSocketCritSec); // Load winsock if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { fprintf(stderr, "unable to load Winsock!\n"); return -1; } gWorkerWindow = MakeWorkerWindow(); printf("Local address: %s; Port: %s; Family: %d\n", gBindAddr, gBindPort, gAddressFamily); res = ResolveAddress(gBindAddr, gBindPort, gAddressFamily, gSocketType, gProtocol); if (res == NULL) { fprintf(stderr, "ResolveAddress failed to return any addresses!\n"); return -1; } // For each local address returned, create a listening/receiving socket ptr = res; while (ptr) { PrintAddress(ptr->ai_addr, ptr->ai_addrlen); printf("\n"); sockobj = GetSocketObj(INVALID_SOCKET); // create the socket sockobj->s = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (sockobj->s == INVALID_SOCKET) { fprintf(stderr,"socket failed: %d\n", WSAGetLastError()); return -1; } InsertSocketObj(sockobj); // bind the socket to a local address and port rc = bind(sockobj->s, ptr->ai_addr, ptr->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } if (gProtocol == IPPROTO_TCP) { rc = listen(sockobj->s, 200); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen failed: %d\n", WSAGetLastError()); return -1; } // Register for notification rc = WSAAsyncSelect( sockobj->s, gWorkerWindow, WM_SOCKET, FD_ACCEPT | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAAsyncSelect failed: %d\n", WSAGetLastError()); return -1; } } else { // Register for notification rc = WSAAsyncSelect( sockobj->s, gWorkerWindow, WM_SOCKET, FD_READ | FD_WRITE | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAAsyncSelect failed: %d\n", WSAGetLastError()); return -1; } } ptr = ptr->ai_next; } // free the addrinfo structure for the 'bind' address freeaddrinfo(res); gStartTime = gStartTimeLast = lastprint = GetTickCount(); // Start a thread to print statistics hThread = CreateThread(NULL, 0, StatisticsThread, NULL, 0, NULL); if (hThread == NULL) { fprintf(stderr, "CreateThread failed: %d\n", WSAGetLastError()); return -1; } CloseHandle(hThread); while(rc = GetMessage(&msg, NULL, 0, 0)) { if (rc == -1) { fprintf(stderr, "GetMessage() failed with error %d\n", GetLastError()); return -1; } TranslateMessage(&msg); DispatchMessage(&msg); } WSACleanup(); DeleteCriticalSection(&gSocketCritSec); return 0; }
//****************************************************************************** // Routine: // CreateFilter // // Arguments: // ppFilter - double ptr to Filter struct in which the function returns the filter // Address - destination address of the outgoing packets of interest. // Port - destination port of the outgoing packets of interest. // ProtocolId - protocol of the outgoing packets of interest. // // Description: // The function returns a tc filter in ppFilter on success // //****************************************************************************** BOOL CreateFilter(PTC_GEN_FILTER *ppFilter, SOCKADDR_STORAGE Address, USHORT Port, UCHAR ProtocolId) { BOOL status = FALSE; USHORT AddressFamily = Address.ss_family; PTC_GEN_FILTER pFilter = NULL; PIP_PATTERN pPattern = NULL; PIP_PATTERN pMask = NULL; // // Print out the Filter Parameters // printf("Filter Parameters:\n"); PrintAddress(&Address); printf("\tDest Port: %u\n", Port); printf("\tProtocol: "); switch (ProtocolId) { case IPPROTO_IP: { printf("IP\n"); break; } case IPPROTO_TCP: { printf("TCP\n"); break; } case IPPROTO_UDP: { printf("UDP\n"); break; } default: { printf("Invalid Protocol\n"); break; } }; if (AddressFamily != AF_INET) { goto Exit; } // // Allocate memory for the filter // pFilter = (PTC_GEN_FILTER)malloc(sizeof(TC_GEN_FILTER)); if (!pFilter) { printf("Error, No memory for filter\n"); goto Exit; } ZeroMemory(pFilter, sizeof(TC_GEN_FILTER)); // // Allocate memory for the pattern and mask // pPattern = (PIP_PATTERN)malloc(sizeof(IP_PATTERN)); pMask = (PIP_PATTERN)malloc(sizeof(IP_PATTERN)); if (!pPattern || !pMask) { goto Exit; } memset(pPattern, 0, sizeof(IP_PATTERN)); pPattern->DstAddr = ((SOCKADDR_IN *)&Address)->sin_addr.s_addr; pPattern->tcDstPort = htons(Port); pPattern->ProtocolId = ProtocolId; memset(pMask, (ULONG)-1, sizeof(IP_PATTERN)); // // Set the source address and port to wildcard // 0 -> wildcard, 0xFF-> exact match // pMask->SrcAddr = 0; pMask->tcSrcPort = 0; // // If the user specified 0 for dest port, dest address or protocol // set the appropriate mask as wildcard // 0 -> wildcard, 0xFF-> exact match // if (pPattern->tcDstPort == 0) { pMask->tcDstPort = 0; } if (pPattern->ProtocolId == 0) { pMask->ProtocolId = 0; } if (pPattern->DstAddr == 0) { pMask->DstAddr = 0; } pFilter->AddressType = NDIS_PROTOCOL_ID_TCP_IP; pFilter->PatternSize = sizeof(IP_PATTERN); pFilter->Pattern = pPattern; pFilter->Mask = pMask; // // Delete any previous instances of the Filter // DeleteFilter(ppFilter); *ppFilter = pFilter; status = TRUE; Exit: if (!status) { printf("Filter Creation Failed\n"); DeleteFilter(&pFilter); } else { printf("Filter Creation Succeeded\n"); } return status; }
PRIntn main(PRIntn argc, char **argv) { PRStatus rv; PLOptStatus os; PRHostEnt host; PRProtoEnt proto; PRBool ipv6 = PR_FALSE; const char *name = NULL; PRBool failed = PR_FALSE; PLOptState *opt = PL_CreateOptState(argc, argv, "h6"); err = PR_GetSpecialFD(PR_StandardError); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { if (PL_OPT_BAD == os) continue; switch (opt->option) { case 0: /* Name of host to lookup */ name = opt->value; break; case '6': /* Turn on IPv6 mode */ ipv6 = PR_TRUE; break; case 'h': /* user wants some guidance */ default: Help(); /* so give him an earful */ return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); if (ipv6) { rv = PR_SetIPv6Enable(ipv6); if (PR_FAILURE == rv) { failed = PR_TRUE; PL_FPrintError(err, "PR_SetIPv6Enable"); } } { if (NULL == name) { char *me = (char*)PR_MALLOC(DNS_BUFFER); rv = PR_GetSystemInfo(PR_SI_HOSTNAME, me, DNS_BUFFER); if (PR_FAILURE == rv) { failed = PR_TRUE; PL_FPrintError(err, "PR_GetHostName"); return 2; } name = me; /* just leak the storage */ } } { char buffer[HOST_BUFFER]; PR_fprintf(err, "Translating the name %s ...", name); rv = PR_GetHostByName(name, buffer, sizeof(buffer), &host); if (PR_FAILURE == rv) { failed = PR_TRUE; PL_FPrintError(err, "PR_GetHostByName"); } else { PRIntn index = 0; PRNetAddr address; PR_fprintf(err, "success .. enumerating results\n"); do { index = PR_EnumerateHostEnt(index, &host, 0, &address); if (index > 0) PrintAddress(&address); else if (-1 == index) { failed = PR_TRUE; PL_FPrintError(err, "PR_EnumerateHostEnt"); } } while (index > 0); } } { char buffer[PROTO_BUFFER]; /* ** Get Proto by name/number */ rv = PR_GetProtoByName("tcp", &buffer[1], sizeof(buffer) - 1, &proto); rv = PR_GetProtoByNumber(6, &buffer[3], sizeof(buffer) - 3, &proto); } return (failed) ? 1 : 0; }
static void PR_CALLBACK Clientel(void *arg) { PRStatus rv; PRFileDesc *xport; PRInt32 bytes, sampled; PRIntervalTime now, interval; PRBool do_display = PR_FALSE; Shared *shared = (Shared*)arg; char *buffer = (char*)PR_Malloc(buffer_size); PRNetAddr *server_address = &shared->server_address; PRIntervalTime connect_timeout = PR_SecondsToInterval(5); PRIntervalTime sampling_interval = PR_SecondsToInterval(SAMPLING_INTERVAL); PR_fprintf(err, "Client connecting to "); (void)PrintAddress(server_address); do { xport = PR_Socket(domain, PR_SOCK_STREAM, protocol); if (NULL == xport) { PL_FPrintError(err, "PR_Socket"); return; } if (xport_buffer != -1) { PRSocketOptionData data; data.option = PR_SockOpt_RecvBufferSize; data.value.recv_buffer_size = (PRSize)xport_buffer; rv = PR_SetSocketOption(xport, &data); if (PR_FAILURE == rv) PL_FPrintError(err, "PR_SetSocketOption - ignored"); data.option = PR_SockOpt_SendBufferSize; data.value.send_buffer_size = (PRSize)xport_buffer; rv = PR_SetSocketOption(xport, &data); if (PR_FAILURE == rv) PL_FPrintError(err, "PR_SetSocketOption - ignored"); } rv = PR_Connect(xport, server_address, connect_timeout); if (PR_FAILURE == rv) { PL_FPrintError(err, "PR_Connect"); if (PR_IO_TIMEOUT_ERROR != PR_GetError()) PR_Sleep(connect_timeout); PR_Close(xport); /* delete it and start over */ } } while (PR_FAILURE == rv); do { bytes = PR_Recv( xport, buffer, buffer_size, 0, PR_INTERVAL_NO_TIMEOUT); PR_Lock(shared->ml); now = PR_IntervalNow(); shared->sampled += bytes; interval = now - shared->timein; if (interval > sampling_interval) { sampled = shared->sampled; shared->timein = now; shared->sampled = 0; do_display = PR_TRUE; } PR_Unlock(shared->ml); if (do_display) { PRUint32 rate = sampled / PR_IntervalToMilliseconds(interval); PR_fprintf(err, "%u streams @ %u Kbytes/sec\n", shared->threads, rate); do_display = PR_FALSE; } } while (bytes > 0); } /* Clientel */
// // Function: main // // Description: // Parse the command line arguments, load the Winsock library, // create a socket and join the multicast group. If set as a // sender then begin sending messages to the multicast group; // otherwise, call recvfrom() to read messages send to the // group. // int _cdecl main(int argc, char **argv) { WSADATA wsd; SOCKET s, sc; SOCKADDR_STORAGE remote; struct addrinfo *resmulti=NULL, *resif=NULL, *resbind=NULL; char *buf=NULL; int remotelen, err, rc, i=0; // Parse the command line ValidateArgs(argc, argv); // Load Winsock if (WSAStartup(MAKEWORD(1, 1), &wsd) != 0) { printf("WSAStartup failed\n"); return -1; } // Resolve the multicast address resmulti = ResolveAddress(gMulticast, gPort, AF_INET, 0, 0); if (resmulti == NULL) { fprintf(stderr, "Unable to convert multicast address '%s': %d\n", gMulticast, WSAGetLastError()); return -1; } // // Create the socket. In Winsock 1 you don't need any special // flags to indicate multicasting. // s = socket(resmulti->ai_family, gSocketType, gProtocol); if (s == INVALID_SOCKET) { printf("socket failed with: %d\n", WSAGetLastError()); return -1; } printf("socket handle = 0x%p\n", s); // Allocate the send/receive buffer buf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, gBufferSize); if (buf == NULL) { fprintf(stderr, "HeapAlloc failed: %d\n", GetLastError()); return -1; } if (bSender) { // Bind to the wildcard address resbind = ResolveAddress(NULL, gPort, AF_INET, 0, 0); if (resbind == NULL) { fprintf(stderr, "Unable to obtain bind address!\n"); return -1; } // Bind the socket rc = bind(s, resbind->ai_addr, resbind->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } freeaddrinfo(resbind); // If sepcified, set the send interface if (gInterfaceCount == 1) { resif = ResolveAddress(gListenInterface[0], gPort, AF_INET, 0, 0); if (resif == NULL) { return -1; } rc = SetSendInterface(s, resif); freeaddrinfo(resif); // Set the TTL to something else. The default TTL is one. rc = SetMulticastTtl(s, resmulti->ai_family, gTtl); if (rc == SOCKET_ERROR) { return -1; } } // If specified set the late joiner option if (gLateJoin != -1) { SetLateJoin(s, gLateJoin); } // If specified set the window paramters if (bSetSendWindow) { SetWindowSize(s, gWindowSizeBytes, gWindowSizeMSec, gWindowRateKbitsSec); } // If specified set the FEC paramters if (bUseFec == TRUE) { SetFecParameters(s, gFecBlockSize, gFecGroupSize, bFecOnDemand, gFecProActive); } // Connect the socket to the multicast group the session is to be on rc = connect(s, resmulti->ai_addr, resmulti->ai_addrlen); if (rc == SOCKET_ERROR) { printf("connect failed: %d\n", WSAGetLastError()); return -1; } memset(buf, '^', gBufferSize); // Send some data for(i=0; i < gCount ; i++) { rc = send( s, buf, gBufferSize, 0 ); if (rc == SOCKET_ERROR) { fprintf(stderr, "send failed with: %d\n", WSAGetLastError()); return -1; } printf("SENT %d bytes\n", rc); } } else { // Bind the socket to the multicast address on which the session will take place rc = bind(s, resmulti->ai_addr, resmulti->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } printf("Binding to "); PrintAddress(resmulti->ai_addr, resmulti->ai_addrlen); printf("\n"); // Add each supplied interface as a receive interface if (gInterfaceCount > 0) { for(i=0; i < gInterfaceCount ;i++) { resif = ResolveAddress(gListenInterface[i], "0", AF_INET, 0, 0); if (resif == NULL) { return -1; } rc = AddReceiveInterface(s, resif); freeaddrinfo(resif); } } // Listen for sessions rc = listen(s, 1); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen failed: %d\n", WSAGetLastError()); return -1; } // Wait for a session to become available remotelen = sizeof(remote); sc = accept(s, (SOCKADDR *)&remote, &remotelen); if (sc == INVALID_SOCKET) { fprintf(stderr, "accept failed: %d\n", WSAGetLastError()); return -1; } printf("Join multicast session from: "); PrintAddress((SOCKADDR *)&remote, remotelen); printf("\n"); while (1) { // Receive data until an error or until the session is closed rc = recv(sc, buf, gBufferSize, 0); if (rc == SOCKET_ERROR) { if ((err = WSAGetLastError()) != WSAEDISCON) { fprintf(stderr, "recv failed: %d\n", err); } break; } else { printf("received %d bytes\n", rc); } } // Close the session socket closesocket(sc); } // Clean up freeaddrinfo(resmulti); closesocket(s); WSACleanup(); return 0; }
AStringVector cNetwork::EnumLocalIPAddresses(void) { AStringVector res; #ifdef _WIN32 // Query the OS for all adapters' addresses: char buffer[64 KiB]; // A buffer backing the address list PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&buffer); ULONG outBufLen = sizeof(buffer); DWORD dwRetVal = GetAdaptersAddresses( AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, nullptr, pAddresses, &outBufLen ); if (dwRetVal != ERROR_SUCCESS) { LOG("GetAdaptersAddresses() failed: %u", dwRetVal); return res; } // Enumerate all active adapters for (auto pCurrAddresses = pAddresses; pCurrAddresses != nullptr; pCurrAddresses = pCurrAddresses->Next) { if (pCurrAddresses->OperStatus != IfOperStatusUp) { // Adapter not active, skip it: continue; } // Collect all IP addresses on this adapter: for (auto pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != nullptr; pUnicast = pUnicast->Next) { auto Address = PrintAddress(pUnicast->Address); if (!Address.empty()) { res.push_back(Address); } } // for pUnicast } // for pCurrAddresses #else // _WIN32 struct ifaddrs * ifAddrStruct = nullptr; getifaddrs(&ifAddrStruct); for (auto ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa->ifa_addr == nullptr) { continue; } auto Address = PrintAddress(ifa); if (!Address.empty()) { res.emplace_back(Address); } } if (ifAddrStruct != nullptr) { freeifaddrs(ifAddrStruct); } #endif // else _WIN32 return res; }
void CreateDatabase( struct Connection* conn ) { for ( int i=0; i<MAX_ROWS; i++ ) { struct Address addr = { .id = i, .set = 0 }; conn->db->rows[ i ] = addr; } } void SetDatabase( struct Connection* conn, int id, const char* name, const char* email ) { struct Address* addr = &conn->db->rows[ id ]; if ( addr->set ) { Die( "Already set, delete it first" ); } addr->set = 1; char* res = strncpy( addr->name, name, MAX_DATA ); if ( !res ) { Die( "Name copy failed." ); } res = strncpy( addr->email, email, MAX_DATA ); if ( !res ) { Die( "Email copy failed." ); } } void GetDatabase( struct Connection* conn, int id ) { struct Address* addr = &conn->db->rows[ id ]; if ( addr->set ) { PrintAddress( addr ); } else { Die( "ID is not set." ); } } void DeleteDatabase( struct Connection* conn, int id ) { struct Address addr = { .id = id, .set = 0 }; conn->db->rows[ id ] = addr; } void ListDatabase( struct Connection* conn ) { struct Database* db = conn->db; for ( int i=0; i<MAX_ROWS; i++ ) { struct Address* cur = &db->rows[ i ]; if ( cur->set ) { PrintAddress( cur ); } } } int main( int argc, char* argv[] ) { if ( argc < 3 ) { Die( "USAGE: ex17 <dbfile> <action> [action params]" ); } char* filename = argv[ 1 ]; char action = argv[ 2 ][ 0 ]; struct Connection* conn = OpenDatabase( filename, action ); int id = 0; if ( argc > 3 ) { id = atoi( argv[ 3 ] ); } if ( id>= MAX_ROWS ) { Die( "There is not that many records." ); } if ( action == 'c' ) { CreateDatabase( conn ); WriteDatabase( conn ); } else if ( action == 'g' ) { if ( argc != 4 ) { Die( "Need an id to get" ); } else { GetDatabase( conn, id ); } } else if ( action == 's' ) { if ( argc != 6 ) { Die( "Need id, name, email to set" ); } else { SetDatabase( conn, id, argv[ 4 ], argv[ 5 ] ); WriteDatabase( conn ); } } else if ( action == 'd' ) { if ( argc != 4 ) { Die( "Need id to delete" ); } else { DeleteDatabase( conn, id ); WriteDatabase( conn ); } } else if ( action == 'l' ) { ListDatabase( conn ); } else { Die( "Invalid action, only: c=create, g=get, d=delete, l=list" ); } CloseDatabase( conn ); return 0; }
void ListAddress(void) { if (printState && ((1 << ListPC) & listStatus)) PrintAddress(); } /* End ListAddress */
static void AcceptingThread(void *arg) { PRStatus rv; PRInt32 bytes; PRSize buf_size = BUF_SIZE; PRUint8 buf[BUF_SIZE + (2 * sizeof(PRNetAddr)) + 32]; PRNetAddr *accept_addr, *listen_addr = (PRNetAddr*)arg; PRFileDesc *accept_sock, *listen_sock = PR_NewTCPSocket(); PRFileDesc *layer; PRSocketOptionData sock_opt; if (NULL == listen_sock) { PL_FPrintError(err_out, "PR_NewTCPSocket (server) failed"); PR_ProcessExit(1); } layer = PR_CreateIOLayerStub(emu_layer_ident, &emu_layer_methods); if (NULL == layer) { PL_FPrintError(err_out, "PR_CreateIOLayerStub (server) failed"); PR_ProcessExit(1); } if (PR_PushIOLayer(listen_sock, PR_TOP_IO_LAYER, layer) == PR_FAILURE) { PL_FPrintError(err_out, "PR_PushIOLayer (server) failed"); PR_ProcessExit(1); } sock_opt.option = PR_SockOpt_Reuseaddr; sock_opt.value.reuse_addr = PR_TRUE; rv = PR_SetSocketOption(listen_sock, &sock_opt); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_SetSocketOption (server) failed"); PR_ProcessExit(1); } rv = PR_Bind(listen_sock, listen_addr); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Bind (server) failed"); PR_ProcessExit(1); } rv = PR_Listen(listen_sock, 10); if (PR_FAILURE == rv) { PL_FPrintError(err_out, "PR_Listen (server) failed"); PR_ProcessExit(1); } bytes = PR_AcceptRead( listen_sock, &accept_sock, &accept_addr, buf, buf_size, accept_timeout); if (-1 == bytes) PL_FPrintError(err_out, "PR_AcceptRead (server) failed"); else { PrintAddress(accept_addr); PR_fprintf( std_out, "(Server) read [0x%p..0x%p) %s\n", buf, &buf[BUF_SIZE], buf); bytes = PR_Write(accept_sock, buf, bytes); rv = PR_Shutdown(accept_sock, PR_SHUTDOWN_BOTH); if (PR_FAILURE == rv) PL_FPrintError(err_out, "PR_Shutdown (server) failed"); } if (-1 != bytes) { rv = PR_Close(accept_sock); if (PR_FAILURE == rv) PL_FPrintError(err_out, "PR_Close (server) failed"); } rv = PR_Close(listen_sock); if (PR_FAILURE == rv) PL_FPrintError(err_out, "PR_Close (server) failed"); } /* AcceptingThread */
void AMXStackFramePrinter::PrintReturnAddress(const AMXStackFrame &frame) { PrintAddress(frame.return_address()); }