/** * Create a new socket handle. * @param family Must be {@code AF_INET} * @param type Either SOCK_DGRAM or SOCK_STREAM * @param protocol Either IPPROTO_UDP or IPPROTO_TCP * @return */ sock_handle_t socket_create(uint8_t family, uint8_t type, uint8_t protocol, uint16_t port, network_interface_t nif) { if (family!=AF_INET || !((type==SOCK_DGRAM && protocol==IPPROTO_UDP) || (type==SOCK_STREAM && protocol==IPPROTO_TCP))) return SOCKET_INVALID; sock_handle_t result = SOCKET_INVALID; socket_t* socket = new socket_t(); if (socket) { wiced_result_t wiced_result; socket->set_type((protocol==IPPROTO_UDP ? socket_t::UDP : socket_t::TCP)); if (protocol==IPPROTO_TCP) { wiced_result = wiced_tcp_create_socket(tcp(socket), wiced_wlan_interface(nif)); } else { wiced_result = wiced_udp_create_socket(udp(socket), port, wiced_wlan_interface(nif)); } if (wiced_result!=WICED_SUCCESS) { socket->set_type(socket_t::NONE); delete socket; result = as_sock_result(wiced_result); } else { SocketListLock lock(list_for(socket)); add_socket(socket); result = as_sock_result(socket); } } return result; }
/* -----------------------------------------------------------------------------------------------------------*/ void ip( int packet_lenght , char *buffer ) { struct ETH_header *ETH_packet; // ETH_struct anlegen ETH_packet = (struct ETH_header *)&buffer[0]; struct IP_header *IP_packet; // IP_struct anlegen IP_packet = ( struct IP_header *)&buffer[ETHERNET_HEADER_LENGTH]; // checke mal ob dat überhaupt für uns ist // if ( IP_packet->IP_DestinationIP != myIP || IP_packet->IP_DestinationIP != 0xffffffff ) return; // if ( ( IP_packet->IP_Flags_Fragmentoffset & htons( FRAGMENTOFFSET_bm ) ) == 0 ) // { switch ( IP_packet->IP_Protocol ) { case 0x01: if ( IP_packet->IP_DestinationIP != myIP ) return; icmp( packet_lenght , buffer); break; #if defined(TCP) case 0x06: if ( IP_packet->IP_DestinationIP != myIP ) return; tcp( packet_lenght , buffer ); break; #endif #if defined(UDP) case 0x11: udp( packet_lenght , buffer ); break; #endif default: break; } // } }
static int parse_ipv4(void *data, uint64_t nh_off, void *data_end) { struct iphdr *iph; uint64_t ihl_len; iph = data + nh_off; if (iph + 1 > data_end) return 0; if (ip_is_fragment(iph)) return 0; ihl_len = iph->ihl * 4; if (iph->protocol == IPPROTO_IPIP) { iph = data + nh_off + ihl_len; if (iph + 1 > data_end) return 0; ihl_len += iph->ihl * 4; } if (iph->protocol == IPPROTO_TCP) return tcp(data, nh_off + ihl_len, data_end); else if (iph->protocol == IPPROTO_UDP) return udp(data, nh_off + ihl_len, data_end); return 0; }
static int parse_ipv6(void *data, uint64_t nh_off, void *data_end) { struct ipv6hdr *ip6h; struct iphdr *iph; uint64_t ihl_len = sizeof(struct ipv6hdr); uint64_t nexthdr; ip6h = data + nh_off; if (ip6h + 1 > data_end) return 0; nexthdr = ip6h->nexthdr; if (nexthdr == IPPROTO_IPIP) { iph = data + nh_off + ihl_len; if (iph + 1 > data_end) return 0; ihl_len += iph->ihl * 4; nexthdr = iph->protocol; } else if (nexthdr == IPPROTO_IPV6) { ip6h = data + nh_off + ihl_len; if (ip6h + 1 > data_end) return 0; ihl_len += sizeof(struct ipv6hdr); nexthdr = ip6h->nexthdr; } if (nexthdr == IPPROTO_TCP) return tcp(data, nh_off + ihl_len, data_end); else if (nexthdr == IPPROTO_UDP) return udp(data, nh_off + ihl_len, data_end); return 0; }
int main() { // init udp std::cout << "init UDP" << std::endl; udp_sender udp("192.168.137.1", 18111); // init & calibrate gyro std::cout << "initializing gyro" << std::endl; while (true) { if (gyro.calibrate()) { std::cout << "calibrated" << std::endl; break; } std::cout << "couldn't calibrate" << std::endl; } // evaluate attitude quat q = quat::rotation(0.0, vec3d(1, 0, 0)); // all the variables are in usec int64_t const desc = 50 * 1000; int64_t t_up, t1, t2; t_up = t1 = t2 = sysclock.usec(); while (true) { vec3d w; t_up = t_up + desc; do { w = gyro.angular_velocity(); t1 = t2; t2 = sysclock.usec(); q = q + 0.5 * q * w * (t2 - t1) * 0.000001; // usec to sec q.normalize(); // to fix integration error } while (t_up > t2); udp.send(q); } }
sock_result_t socket_sendto(sock_handle_t sd, const void* buffer, socklen_t len, uint32_t flags, sockaddr_t* addr, socklen_t addr_size) { socket_t* socket = from_handle(sd); wiced_result_t result = WICED_INVALID_SOCKET; if (is_open(socket) && is_udp(socket)) { std::lock_guard<socket_t> lk(*socket); SOCKADDR_TO_PORT_AND_IPADDR(addr, addr_data, port, ip_addr); uint16_t available = 0; wiced_packet_t* packet = NULL; uint8_t* data; if ((result=wiced_packet_create_udp(udp(socket), len, &packet, &data, &available))==WICED_SUCCESS) { size_t size = std::min(available, uint16_t(len)); memcpy(data, buffer, size); /* Set the end of the data portion */ wiced_packet_set_data_end(packet, (uint8_t*) data + size); result = wiced_udp_send(udp(socket), &ip_addr, port, packet); len = size; } } // return negative value on error, or length if successful. return result ? -result : len; }
int main(){ RobotManager manager; UDPServer udp(manager); int cons = 0; while(true){ if(manager.size() > cons){ std::cout << manager.getDetails(); auto rosbee = manager.getRobot<Rosbee>(cons); rosbee->init(); cons++; } } exit(0); }
void Topology::setRootServers(const Dictionary &sn) { std::map< Identity,std::vector<InetAddress> > m; for(Dictionary::const_iterator d(sn.begin());d!=sn.end();++d) { if ((d->first.length() == ZT_ADDRESS_LENGTH_HEX)&&(d->second.length() > 0)) { try { Dictionary snspec(d->second); std::vector<InetAddress> &a = m[Identity(snspec.get("id"))]; std::string udp(snspec.get("udp",std::string())); if (udp.length() > 0) a.push_back(InetAddress(udp)); } catch ( ... ) { TRACE("root server list contained invalid entry for: %s",d->first.c_str()); } } } this->setRootServers(m); }
void startup(void) { printf("System is Starting...\n"); printf("Initializing Serial Port...\n"); if(roboLinkInit()>0) { printf("RoboLink is Ready.\n"); } else { printf("RoboLink Init Failed.\n"); } boost::thread udp(&udpServerTask); printf("UDP Server is Running!\n"); boost::thread tcp(&tcpServerTask); printf("TCP Server is Running!\n"); boost::thread control(&roboControlLoop); printf("Robot Control Loop is Running!!"); triZero(); }
/* -----------------------------------------------------------------------------------------------------------*/ void ip( unsigned int packet_lenght , unsigned char *buffer ) { struct ETH_header *ETH_packet; // ETH_struct anlegen ETH_packet = (struct ETH_header *)&buffer[0]; struct IP_header *IP_packet; // IP_struct anlegen IP_packet = ( struct IP_header *)&buffer[ETHERNET_HEADER_LENGTH]; // checke mal ob dat überhaupt für uns ist // if ( IP_packet->IP_DestinationIP != myIP || IP_packet->IP_DestinationIP != 0xffffffff ) return; switch ( IP_packet->IP_Protocol ) { case 0x01: if (( IP_packet->IP_DestinationIP != myIP )&&( IP_packet->IP_DestinationIP !=myBroadcast)) return; icmp( packet_lenght , buffer); break; case 0x06: if ( IP_packet->IP_DestinationIP != myIP ) return; tcp( packet_lenght , buffer ); break; case 0x11: udp( packet_lenght , buffer ); break; } }
sock_result_t socket_receivefrom(sock_handle_t sd, void* buffer, socklen_t bufLen, uint32_t flags, sockaddr_t* addr, socklen_t* addrsize) { socket_t* socket = from_handle(sd); volatile wiced_result_t result = WICED_INVALID_SOCKET; uint16_t read_len = 0; if (is_open(socket) && is_udp(socket)) { std::lock_guard<socket_t> lk(*socket); wiced_packet_t* packet = NULL; // UDP receive timeout changed to 0 sec so as not to block if ((result=wiced_udp_receive(udp(socket), &packet, WICED_NO_WAIT))==WICED_SUCCESS) { wiced_ip_address_t wiced_ip_addr; uint16_t port; if ((result=wiced_udp_packet_get_info(packet, &wiced_ip_addr, &port))==WICED_SUCCESS) { uint32_t ipv4 = GET_IPV4_ADDRESS(wiced_ip_addr); addr->sa_data[0] = (port>>8) & 0xFF; addr->sa_data[1] = port & 0xFF; addr->sa_data[2] = (ipv4 >> 24) & 0xFF; addr->sa_data[3] = (ipv4 >> 16) & 0xFF; addr->sa_data[4] = (ipv4 >> 8) & 0xFF; addr->sa_data[5] = ipv4 & 0xFF; result=read_packet(packet, (uint8_t*)buffer, bufLen, &read_len); }
/* Entry point */ int main(int argc, char** argv) { std::ifstream config_file("metaserver-ng.conf"); boost::asio::io_service io_service; boost::program_options::variables_map vm; int port = 8453; std::string ip = "0.0.0.0"; /** * Argument Wrangling * * Note: not exactly the most friendly option parsing I've seen */ boost::program_options::options_description desc( "MetaServer Configuration" ); /** * Note: options inside the configuration file that are NOT listed here * become ignored and are not accessible. */ desc.add_options() ( "help,h", "Display help message" ) ( "server.port,p", boost::program_options::value<int>(), "Server bind port. \nDefault:8543" ) ( "server.ip", boost::program_options::value<std::string>(), "Server bind IP. \nDefault:0.0.0.0" ) ( "server.daemon", boost::program_options::value<std::string>(), "Daemonize after startup [true|false].\nDefault: true" ) ( "server.logfile", boost::program_options::value<std::string>(), "Server logfile location.\nDefault: ~/.metaserver-ng/metaserver-ng.log" ) ( "server.client_stats", boost::program_options::value<std::string>(), "Keep internals stats [true|false]. This can affect performance.\nDefault: false" ) ( "server.server_stats", boost::program_options::value<std::string>(), "Keep internals stats [true|false]. This can affect performance.\nDefault: false" ) ( "logging.server_sessions", boost::program_options::value<std::string>(), "Output server sessions to logfile [true|false]. \nDefault: false" ) ( "logging.client_sessions", boost::program_options::value<std::string>(), "Output client sessions to logfile [true|false]. \nDefault: false" ) ( "logging.packet_logging", boost::program_options::value<std::string>(), "Output all packets to logfile [true|false]. \nDefault: false" ) ( "logging.packet_logfile", boost::program_options::value<std::string>(), "Packet logfile location.\nDefault: ~/.metaserver-ng/packetlog.bin" ) ( "security.auth_scheme", boost::program_options::value<std::string>(), "What method of authentication to use [none|server|delegate|both].\nDefault: none" ) ( "performance.max_server_sessions", boost::program_options::value<int>(), "Max number of server sessions [1-32768].\nDefault: 1024" ) ( "performance.max_client_sessions", boost::program_options::value<int>(), "Max number of client sessions [1-32768].\nDefault: 4096") ( "performance.server_session_expiry_seconds", boost::program_options::value<int>(), "Expiry in seconds for server sessions [300-3600].\nDefault: 300" ) ( "performance.client_session_expiry_seconds", boost::program_options::value<int>(), "Expiry in seconds for client sessions [300-3600].\nDefault: 300" ) ; /** * Create our metaserver */ MetaServer ms(io_service); try { boost::program_options::store( boost::program_options::parse_command_line(argc, argv, desc), vm ); boost::program_options::store( boost::program_options::parse_config_file(config_file, desc, true), vm ); boost::program_options::notify(vm); /** * Special case for help */ if ( vm.count("help") ) { std::cout << desc << std::endl; return 1; } /** * The only real options that we need to process outside of the * metaesrver as it affects the handlers */ if ( vm.count("server.port") ) port=vm["server.port"].as<int>(); if ( vm.count("server.ip") ) ip=vm["server.ip"].as<std::string>(); /** * Register the configuration. */ ms.registerConfig(vm); /** * Go daemon if needed */ if ( ms.isDaemon() ) { ms.getLogger().info("Running as a daemon"); daemon(0,0); } /** * Define Handlers */ //MetaServerHandlerTCP tcp(ms, io_service, ip, port); MetaServerHandlerUDP udp(ms, io_service, ip, port); /** * This is the async loop */ for(;;) { try { /* * We run and complete normally */ io_service.run(); break; } catch(std::exception ex) { /* * This will catch exceptions inside the io_service loop/handler. * * If we have a handler exception this should account as a reasonable * effort to resume operation despite the error */ std::cerr << "IOService Loop Exception:" << ex.what() << std::endl; } } } catch (std::exception& e) { /* * This will catch exceptions during the startup etc */ std::cerr << "Exception: " << e.what() << std::endl; } std::cout << "All Done!" << std::endl; return 0; }
int main(int argc, char ** argv) { char btaddr[18] = "00:0B:0B:0B:03:84"; if(argc>1) strncpy(btaddr, argv[1], strlen(btaddr)); char filename[80]; snprintf(filename, 80, "%d.nmea", time(NULL)); // standard_input std_in; serial_port std_in("/dev/tts/0"); // rfcomm_socket std_in("00:0B:0B:0B:03:84"); tokenizer tok('\n'); nmea_parser nmea; variometer vario; speedometer ais; udp_socket udp("255.255.255.255", 1771); file_output fileout(filename); posix_thread t(&std_in); std_in.add_output(&tok); tok.add_output(&nmea); tok.add_output(&udp); tok.add_output(&fileout); nmea.add(&vario); nmea.add(&ais); color white((unsigned char)0xff, 0xff, 0xff, 0xff); color black((unsigned char)0x00, 0x00, 0x00, 0xff); color green((unsigned char)0x00, 0x99, 0x00, 0xff); linux_framebuffer fb; fb.setcolor(green); fb.clear(); fb.setcolor(black); int oldx=320; int oldy=240; int newx=320; int newy=240; float r=120.0f; for(float f=0; f<6.283f; f+=(3.1415/180.0f)) { newx = (int)((cos(f) * r) + 120.0f); newy = (int)((sin(f) * r) + 200.0f); fb.line(oldx, oldy, newx, newy); int deg = (int)((f/6.283f)*360.0f); oldx=newx; oldy=newy; } fb.triangle(120, 80, 130, 70, 110, 70); fb.triangle(120, 190, 110, 200, 130, 200); fb.line(120, 190, 120, 180); fb.triangle(150, 170, 140, 180, 160, 180); fb.line(150,170, 150, 160); int y=180; for(int i=5; i>-6; i--) { int col1 = 255-(i*51); int col2 = 255+(i*51); if(i >= 0) { color r((unsigned char)0xff, col1, col1, 0xff); fb.setcolor(r); } else { color b((unsigned char)col2, col2, 0xff, 0xff); fb.setcolor(b); } fb.line(149, y, 149, y+10); fb.line(150, y, 150, y+10); fb.line(151, y, 151, y+10); y+=10; } fb.setcolor(black); fb.triangle(90, 150, 100, 160, 110, 150); fb.line(100, 160, 100, 180); t.start(); pause(); }
int main(int argc, char *argv[]) { string domain, request, options, record; bool n, v, s, r, c, w, d; n = v = s = r = c = w = d = false; // allow unencrypted mode, verbose (show all recursion steps), show data structure, raw (show raw data), show configuration vector<string> encvec; string key; size_t pos = 0; int i = 0; vector<vector<string>> alldecvecs; vector<vector<keyval_t>> allkeyvalvecs; vector<smartrns_conf_t> allconfs; vector<smartrns_data_t> alldatas; vector<string> alldomains; //UDPiface udp("127.0.0.1", 7334); UDPiface udp("178.63.154.91", 7334); if(2==argc){ request = argv[1]; // the domain to query }else if((3==argc) | (4==argc)){ options = argv[1]; if(std::string::npos != options.find_first_of('n')) n = true; if(std::string::npos != options.find_first_of('v')) v = true; if(std::string::npos != options.find_first_of('s')) s = true; if(std::string::npos != options.find_first_of('r')) r = true; if(std::string::npos != options.find_first_of('c')) c = true; if(std::string::npos != options.find_first_of('w')) w = true; if(std::string::npos != options.find_first_of('d')) d = true; request = argv[2]; if(w){ if(4==argc){ record = argv[3]; }else{ cout << "Empty record written!" << endl; } } }else{ cout << endl; cout << "Please specify Domain to lookup!" << endl; cout << endl; cout << "This program is designed to query and decode smartRNS data over standard DNS." << endl << endl; cout << "USAGE: smartRNS_UDP_updater [options] [email protected]" << endl << endl; cout << "options: n - allow unencrypted mode" << endl; cout << " v - verbose: show all cycles" << endl; cout << " s - show data-/config-structure" << endl; cout << " r - raw (decrypted TXT records)" << endl; cout << " c - show config" << endl; cout << " w - write entries" << endl; cout << " d - delete entries" << endl << endl; cout << " Copyright (C) 2014 - 2015 Stefan Helmert <*****@*****.**>" << endl; cout << endl; cout << "Try out writing entries! Please ensure at first that upper level entry has a valid configuration." << endl; cout << endl; cout << "EXAMPLE: smartRNS_UDP_updater w [email protected] \"smartrns.data{entry{type=email;[email protected];push=1;}}\"" << endl; cout << endl; return 0; } smartquery query(request, n); // everything after the @ domain = uritop(request, &pos); key = domain; // show recursive resolve steps for(i=0;i<query.get_no_recursions()-1;i++){ // recursion over all subdomains if(v){ if(r) { cout << "REQUEST" << endl << endl << " " << query.get_domain(i) << endl << endl; print_decvec(query.get_decvec(i)); } if(s) print_key_val_vec(query.get_keyvalvec(i)); // output if(c) print_smartrns_config(query.get_conf(i)); // output print_smartrns_data(query.get_data(i)); // output } } // show result if(r) { cout << "REQUEST" << endl << endl << " " << query.get_domain(-1) << endl << endl; print_decvec(query.get_decvec(-1)); } if(s) print_key_val_vec(query.get_keyvalvec(-1)); // output if(c) print_smartrns_config(query.get_conf(-1)); // output print_smartrns_data(query.get_data(-1)); // output // update entries if(d){ udp.senddata(update_packet_del(0x42, query.get_domain(-1))); } if(w){ encvec.clear(); encvec.push_back(record); key = request; encvec = encrypt(encvec, query.get_conf(-2).salt+key, query.get_conf(-2).contprimenc, query.get_conf(-2).contenc); udp.senddata(update_packet_add_s(0x42, query.get_domain(-1), encvec[0])); } return 0; }
uint16 Process_SNMP(uint8 socket, uint8 *remip, uint16 remport, uint8 *buf, uint16 len) { CUDPData udp(remip, remport, buf, len); snmp.GetSnmpDataInOut()->ReceiverData(&udp); return 0; }
void ReadInterfaceNamesBulk() { BOOL Done=FALSE; char *OIDString; OidVarbind* oid; VbPair* vbp; const char *RawRetP=NULL; Packet* retP; DWORD Retries; DWORD x; /* Counter */ Packet p(GETBULK, 1); // create an SNMP v2c GETBULK command int vbLen; int vbCounter; int len; unsigned int IntNumber; /***************/ /* Set up OIDs */ /***************/ OIDString = (char *)malloc(1000); sprintf(OIDString, "1.3.6.1.2.1.2.2.1.2"); /*************************/ /* Create GETBULK packet */ /*************************/ p.Community(Community); // set the community string p.RequestId(123); // use device number to track the request p.ErrorStatus(0); // set non-repeaters to zero p.ErrorIndex(5); // set number of max-repititions oid = new OidVarbind(OIDString); // OID for first MAC address vbp = new VbPair(oid, NULL); // Create vbpairs p.Add(vbp); // Add vbpair to the packet UdpClient udp(161, Agent); // Set to port 161 and IP address (or host name) udp.Timeout(5); // Set timeout to PollDeviceTimeout udp.ReadBufferSize(65535); // set buffer size to be large enough to handle response /*******************/ /* Collection loop */ /*******************/ IntNumber=0; Done = FALSE; while (!Done) { Retries=0; do { dumpPacket(&p); udp.Send(&p); // Send the packet Retries++; RawRetP = udp.Receive(); // Receive the reply } while ((!RawRetP) && (Retries < 3)); /*************************************/ /* If the packet is valid, save info */ /*************************************/ if ( RawRetP ) { // Determine length and parse packet len = udp.ReadLength(); SnmpParser parser((unsigned char*)RawRetP, len); retP = parser.packet(); if (retP != NULL) { // Packet was parsed successfully if ( retP->RequestId() == 123 ) { // RequestID matches if ( retP->ErrorStatus() == NOERROR ) { // No SNMP error found, learn how many OIDs were returned vbLen = retP->VbListLength(); // Loop through for each returned OID for (vbCounter=1 ; vbCounter <= vbLen ; vbCounter++) { sprintf(OIDString, "%s", retP->VbOID(vbCounter)); if (strncmp(OIDString, "1.3.6.1.2.1.2.2.1.2.", 20) == 0) { // OID is still correct, print the results printf("%s: %s\n", retP->VbOID(vbCounter), retP->VbData(vbCounter)); } else { // OID does not match, we're done Done=TRUE; break; } } // Loop through all OIDs // Set up next packet delete oid; printf("assigning new oid of <%s>\r\n", OIDString); oid = new OidVarbind(OIDString); p.VbList()->FirstVbPair()->OIDVarbind(oid); } else { // ErrorStatus returned an SNMP error printf("ERROR: ErrorStatus returned an SNMP error.\n"); break; } } else { // RequestID does not match printf("ERROR: RequestID does not match.\n"); break; } } else { // Packet could not be parsed correctly, some error somewhere printf("ERROR: Packet could not be parsed. Error code: %u\n", udp.ErrorCode()); break; } /******************************/ /* Delete packet if it exists */ /******************************/ if ( retP != NULL ) { delete retP; retP=NULL; } } else { // No packet received printf("ERROR: No packet returned. Error code: %u\n", udp.ErrorCode()); break; } } free(OIDString); return; }
int main( int argc, char **argv ) { std::string arg_qname, arg_qtype, arg_root_server; po::options_description desc( "DNS Client" ); desc.add_options() ( "help,h", "print this message" ) ( "name,n", po::value<std::string>( &arg_qname ), "qname" ) ( "type,t", po::value<std::string>( &arg_qtype ), "qtype" ) ( "root,r", po::value<std::string>( &arg_root_server )->default_value( DEFAULT_ROOT_SERVER ), "root-server IP address" ); po::variables_map vm; po::store( po::parse_command_line( argc, argv, desc ), vm ); po::notify( vm ); if ( vm.count( "help" ) ) { std::cerr << desc << "\n"; return 0; } dns::MessageInfo message_info; dns::QuestionSectionEntry question; question.domainname = arg_qname; question.type = dns::StringToTypeCode( arg_qtype ); question.klass = dns::CLASS_IN; message_info.question_section.push_back( question ); message_info.id = 1234; message_info.opcode = 0; message_info.query_response = 0; message_info.authoritative_answer = 0; message_info.truncation = 0; message_info.recursion_desired = 0; message_info.recursion_available = 0; message_info.zero_field = 0; message_info.authentic_data = 0; message_info.checking_disabled = 1; message_info.response_code = 0; std::cout << "==== Query ====" << std::endl << message_info << std::endl; WireFormat query_message; dns::generateDNSMessage( message_info, query_message ); ClientParameters udp_param; udp_param.address = arg_root_server; udp_param.port = 53; udpv4::Client udp( udp_param ); udp.sendPacket( query_message ); udpv4::PacketInfo response_message = udp.receivePacket(); dns::MessageInfo res = dns::parseDNSMessage( response_message.begin(), response_message.end() ); std::cout << "==== Response ====" << std::endl << res << std::endl; std::cerr << "Response Type: " << dns::ResponseTypeString( dns::classifyResponse( res ) ) << std::endl; return 0; }
int main(int argc, char* argv[], char* envp[]){ //silence warnings (void)envp; if(argc != 4){ printf("Wrong number of arguments. Usage %s <local port> <remote host> <remote port> \n", argv[0]); return 1; } int listenPort = atoi(argv[1]); //timing synchronization //apps will signal when they're all done pthread_mutex_init(&count_mutex, NULL); pthread_cond_init (&count_threshold_cv, NULL); struct timeval t1; struct timeval t2; // set up network ppETH eth(1, listenPort, argv[3], argv[2]); ppIP ip(2); ppTCP tcp(3); ppUDP udp(4); ppFTP ftp(5); ppTEL tel(6); ppRDP rdp(7); ppDNS dns(8); ftpAPP ftpApplication(5, true); telAPP telApplication(6, true); rdpAPP rdpApplication(7, true); dnsAPP dnsApplication(8, true); eth.registerHLP(ip); ip.registerHLP(tcp); ip.registerHLP(udp); tcp.registerHLP(ftp); tcp.registerHLP(tel); udp.registerHLP(rdp); udp.registerHLP(dns); dns.registerHLP(dnsApplication); ftp.registerHLP(ftpApplication); rdp.registerHLP(rdpApplication); tel.registerHLP(telApplication); ftp.registerLLP(tcp); tel.registerLLP(tcp); rdp.registerLLP(udp); dns.registerLLP(udp); tcp.registerLLP(ip); udp.registerLLP(ip); ip.registerLLP(eth); dnsApplication.registerLLP(dns); ftpApplication.registerLLP(ftp); rdpApplication.registerLLP(rdp); telApplication.registerLLP(tel); ip.start(); tcp.start(); udp.start(); ftp.start(); tel.start(); rdp.start(); dns.start(); //make sure everything is set before we start timing sleep(5); gettimeofday(&t1, NULL); // dnsApplication.startListen(); // ftpApplication.startListen(); // rdpApplication.startListen(); // telApplication.startListen(); dnsApplication.startApplication(); ftpApplication.startApplication(); rdpApplication.startApplication(); telApplication.startApplication(); //wait for apps to finish and then stop timing or whatever pthread_mutex_lock(&count_mutex); while (count<numApps*2) { pthread_cond_wait(&count_threshold_cv, &count_mutex); } pthread_mutex_unlock(&count_mutex); gettimeofday(&t2, NULL); printf("Listening on %d took %f ms\n", listenPort, diffms(t2,t1)); }
/// Construct to represent the IPv4 UDP protocol. static udp v4() { return udp(PF_INET); }
void ip(struct pktinfo *pktinfo) { register const struct ip *ipv4 = NULL; register int ipv4_p = 0; /* next header */ const struct in_addr *ipv4_src = NULL; const struct in_addr *ipv4_dst = NULL; struct addr_4 addr_ipv4; struct udphdr *udphdr = NULL; struct tcphdr *tcphdr = NULL; struct pktinfo n_hdr; u_int32_t src = 0; u_int32_t dst = 0; char *addr = NULL; const u_char *pkt = pktinfo->pkt; bpf_u_int32 len = pktinfo->len; ipv4 = (const struct ip *)pkt; /* next header type code */ ipv4_p = ipv4->ip_p; /* IPv4 address */ ipv4_src = &ipv4->ip_src; ipv4_dst = &ipv4->ip_dst; src = htonl(ipv4_src->s_addr); dst = htonl(ipv4_dst->s_addr); addr_ipv4.src = src; addr_ipv4.dst = dst; len -= sizeof(struct ip); pkt += sizeof(struct ip); n_hdr.len = len; n_hdr.pkt = pkt; addr_ipv4.p_tcp = NULL; addr_ipv4.p_udp = NULL; addr_ipv4.nxtflag = 0; if (ipv4_p == IPPROTO_TCP) { tcphdr = (struct tcphdr *)pkt; addr_ipv4.p_tcp = tcphdr; addr_ipv4.nxtflag = 1; } else if (ipv4_p == IPPROTO_UDP) { udphdr = (struct udphdr *)pkt; addr_ipv4.p_udp = udphdr; addr_ipv4.nxtflag = 2; } addr = v4_addr(&addr_ipv4, encap); encap ++; switch(ipv4_p) { case IPPROTO_IPV4 : /* IP header */ ip(&n_hdr); break; case IPPROTO_TCP : /* tcp */ if (rflag != 1) tcp(&n_hdr); break; case IPPROTO_UDP : /* user datagram protocol */ if (bflag != 1) udp(&n_hdr); break; case IPPROTO_IPV6 : /* IP6 header */ ipv6(&n_hdr); break; default: } /* end of switch */ } /* end of ip() */
/// Construct to represent the IPv6 UDP protocol. static udp v6() { return udp(PF_INET6); }
static udp v4() { return udp(ip::v4); }
int main(void){ init_uart(); uint16_t packet_length, rxstat; uart_puts("beginning startup procedure\r\n"); /*ENC Initialisieren*/ enc28j60Init(); uart_puts("initialization finished\r\n"); //Mac Adresse setzen(stack.h, dort wird auch die Ip festgelegt) nicSetMacAddress(mymac); uart_puts("mac address set\r\n"); /* Leds konfigurieren LEDA : Link status LEDB : Receive activity Led Settings : enc28j60 datasheet, page 11*/ enc28j60PhyWrite(0x14,0b0000010000100000); /* Leds konfigurieren LEDA : Link status LEDB : Blink Fast Led Settings : enc28j60 datasheet, page 11 Auskommentieren, wenn mans lieber blinken sieht ;-) */ //enc28j60PhyWrite(0x14,0b0000010000100000); while(1) { // Buffer des Enc's abhohlen :-) packet_length = enc28j60PacketReceive(BUFFER_SIZE, buffer, &rxstat); // Wenn ein Packet angekommen ist, ist packet_length =! 0 if(packet_length) { packet_length -= 4; struct ETH_frame *frame = (struct ETH_frame *) buffer; frame->type_length = ntohs(frame->type_length); // arping uses unicast after the first by default, but we don't care because performance if(/*(*/rxstat&BROADCAST_BIT /*|| compare_macs(frame->destMac, (uint8_t *) mymac))*/ && frame->type_length == TYPE_ARP) { struct ARP_packet *arp_pkt = (struct ARP_packet *) frame->payload; if(compare_ips(arp_pkt->destIp, (uint8_t *) myip)) { arp(packet_length, buffer); } continue; } if(compare_macs(frame->destMac, (uint8_t *) mymac)) { if(frame->type_length == TYPE_IP4) { struct IP_segment *ip = (struct IP_segment *) frame->payload; if(ip->protocol == TYPE_ICMP) { icmp(packet_length, buffer); continue; } else if(ip->protocol == TYPE_UDP) { struct UDP_packet *pkt = (struct UDP_packet *) ip->payload; pkt->destPort = pkt->destPort; pkt->sourcePort = pkt->sourcePort; if(pkt->destPort == ntohs(7)) { udp(htons(pkt->length), buffer); continue; } if(pkt->destPort == ntohs(85) && compare(pkt->data, "test")) { printinbuffer(pkt->data, "Test erfolgreich!", TERMINATE); udp(18, buffer); continue; } if(pkt->destPort == ntohs(86)) { uart_puts((char*) pkt->data); uart_puts("\r\n"); continue; } } else if(ip->protocol == TYPE_TCP) { uart_puts("received tcp package!\r\n"); #if DEBUG hexdump(ip, 256); #endif struct TCP_segment *tcp = (struct TCP_segment *) ip->payload; if(tcp->sourcePort == ntohs(7)) { } } } } } } return 1; }
/// Construct to represent the IPv6 UDP protocol. static udp v6() { return udp(BOOST_ASIO_OS_DEF(AF_INET6)); }
/// Construct to represent the IPv4 UDP protocol. static udp v4() { return udp(ASIO_OS_DEF(AF_INET)); }