static int run_access_hook(struct daemon_service *service, const char *dir, const char *path, struct hostinfo *hi) { struct child_process child = CHILD_PROCESS_INIT; struct strbuf buf = STRBUF_INIT; const char *argv[8]; const char **arg = argv; char *eol; int seen_errors = 0; *arg++ = access_hook; *arg++ = service->name; *arg++ = path; *arg++ = hi->hostname.buf; *arg++ = get_canon_hostname(hi); *arg++ = get_ip_address(hi); *arg++ = hi->tcp_port.buf; *arg = NULL; child.use_shell = 1; child.argv = argv; child.no_stdin = 1; child.no_stderr = 1; child.out = -1; if (start_command(&child)) { logerror("daemon access hook '%s' failed to start", access_hook); goto error_return; } if (strbuf_read(&buf, child.out, 0) < 0) { logerror("failed to read from pipe to daemon access hook '%s'", access_hook); strbuf_reset(&buf); seen_errors = 1; } if (close(child.out) < 0) { logerror("failed to close pipe to daemon access hook '%s'", access_hook); seen_errors = 1; } if (finish_command(&child)) seen_errors = 1; if (!seen_errors) { strbuf_release(&buf); return 0; } error_return: strbuf_ltrim(&buf); if (!buf.len) strbuf_addstr(&buf, "service rejected"); eol = strchr(buf.buf, '\n'); if (eol) *eol = '\0'; errno = EACCES; daemon_error(dir, buf.buf); strbuf_release(&buf); return -1; }
int process_answer(char *dns_response, int offset) { unsigned char data[200]; int numBytes = 2; // skip initial 2 bytes int type = get_short(dns_response, offset + numBytes); numBytes += 2; // count the type numBytes += 2; // skip the address class (should be 0x0001, IPv4) numBytes += 4; // skip the TTL (recommended cache time) int data_length1 = get_short(dns_response, offset + numBytes); numBytes += 2; if (type == 1) { // this is a normal query response (i.e. name -> address) get_ip_address(dns_response, offset + numBytes, data); numBytes += 4; printf("Response: %u.%u.%u.%u\n", data[0],data[1],data[2],data[3]); } else if (type == 5) { // this is a CNAME query response (i.e. an alias) int data_length = get_domain_name(dns_response, offset + numBytes, data); numBytes += data_length; printf("Alias: %s\n", data); } return numBytes; }
static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx) { struct expand_path_context *context = ctx; struct hostinfo *hi = context->hostinfo; switch (placeholder[0]) { case 'H': strbuf_addbuf(sb, &hi->hostname); return 1; case 'C': if (placeholder[1] == 'H') { strbuf_addstr(sb, get_canon_hostname(hi)); return 2; } break; case 'I': if (placeholder[1] == 'P') { strbuf_addstr(sb, get_ip_address(hi)); return 2; } break; case 'P': strbuf_addbuf(sb, &hi->tcp_port); return 1; case 'D': strbuf_addstr(sb, context->directory); return 1; } return 0; }
/* To get our own IP address we get the locally bound address of the socket that's talking to GULM in the assumption(eek) that it will be on the "right" network in a multi-homed system */ static int get_our_ip_address(char *addr, int *family) { struct utsname info; uname(&info); get_ip_address(info.nodename, addr); return 0; }
/* stores address & subnet in a 'struct cidr' assumes: address is already in 1.2.3.4 format subnet is in the format /24 If subnet is incorrect, returns 1 */ int load_cidr(char *cidr, struct cidr *subnet) { struct in_addr addr, mask, comp; int valid = true; char *address, *copy, *strtok_netmask, *destroyable; static char *netmask; static int netmask_is_allocated = false; if(netmask_is_allocated) { if(netmask != NULL) free(netmask); netmask_is_allocated = false; } copy = safe_strdup(cidr); if (copy == NULL) { return 1; } destroyable = copy; address = strtok(destroyable, "/"); strtok_netmask = strtok(NULL, "/"); if(strtok_netmask == NULL) { netmask = safe_strdup("32"); netmask_is_allocated = true; } else { netmask = safe_strdup(strtok_netmask); netmask_is_allocated = true; } if(netmask == NULL) { netmask_is_allocated = false; return 1; } addr = get_ip_address(address, &valid); if(!valid) return 1; mask = get_netmask(netmask, &valid); if(!valid) return 1; /* we now do a bitwise AND to find out if the network address given is valid */ comp.s_addr = mask.s_addr & addr.s_addr; if(comp.s_addr != addr.s_addr) { return 1; } subnet->address = addr; subnet->netmask = mask; free(copy); return 0; }
/* obtain own host's IPV4 address */ static int get_own_ip_address() /* %ENTRY% */ { char buf[1024]; if(GetHostName(buf,sizeof buf)){ fprintf(stderr,"Can't find hostname\n"); return(-1); } return get_ip_address(buf); }
void Streamer::start() { popper->run(); server->Setup(); set_rvw_config(); set_server_config(); server->Play(); dmgr.start(get_ip_address(), config.port + 1); while (true); }
static int init_tcp(char *interface) { int opt_val; if (interface) { if (get_ip_address(interface, local_ip_addr) != STATUS_SUCCESS) { fprintf(stderr, "get_ip_address for interface failed\n"); return STATUS_ERROR; } } server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { perror("error socket open"); return STATUS_ERROR; } opt_val = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &opt_val, sizeof(int)); bzero((char *) &server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; if (interface) server_addr.sin_addr.s_addr = inet_addr(local_ip_addr); else server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons((unsigned short) local_port_id); if (bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { perror("error in bind"); goto err_close; } if (listen(server_fd, LISTEN_SIZE_QUEUE) < 0) { perror("error in listen"); goto err_close; } return STATUS_SUCCESS; err_close: close(server_fd); return STATUS_ERROR; }
int main(int argc, char **argv){ int dhcp_socket; int result = STATE_UNKNOWN; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts(&argc, argv, progname); if(process_arguments(argc,argv)!=OK){ usage4 (_("Could not parse arguments")); } /* this plugin almost certainly needs root permissions. */ np_warn_if_not_root(); /* create socket for DHCP communications */ dhcp_socket=create_dhcp_socket(); /* get hardware address of client machine */ if(user_specified_mac!=NULL) memcpy(client_hardware_address,user_specified_mac,6); else get_hardware_address(dhcp_socket,network_interface_name); if(unicast) /* get IP address of client machine */ get_ip_address(dhcp_socket,network_interface_name); /* send DHCPDISCOVER packet */ send_dhcp_discover(dhcp_socket); /* wait for a DHCPOFFER packet */ get_dhcp_offer(dhcp_socket); /* close socket we created */ close_dhcp_socket(dhcp_socket); /* determine state/plugin output to return */ result=get_results(); /* free allocated memory */ free_dhcp_offer_list(); free_requested_server_list(); return result; }
static rrh_module_t new_module (unsigned int id) { rrh_module_t rrh_mod; openair0_config_t openair0_cfg; rrh_mod.id=id; rrh_mod.loopback=loopback_flag; rrh_mod.measurements=measurements_flag; /* each module is associated with an ethernet device */ rrh_mod.eth_dev.type=ETH_IF; /* ethernet device is functioning within RRH */ rrh_mod.eth_dev.func_type=RRH_FUNC; /* specify IP address */ get_ip_address(if_name); openair0_cfg.my_ip=&rrh_ip[0]; openair0_cfg.my_port=rrh_port; /* ethernet device initialization */ if (openair0_dev_init_eth(&rrh_mod.eth_dev, &openair0_cfg)<0) { LOG_E(RRH,"Exiting, cannot initialize ethernet interface.\n"); exit(-1); } /* allocate space and specify associated RF device */ openair0_device *oai_dv = (openair0_device *)malloc(sizeof(openair0_device)); memset(oai_dv,0, sizeof(openair0_device)); #ifdef EXMIMO rrh_mod.devs=oai_dv; rrh_mod.devs->type=EXMIMO_IF; LOG_I(RRH,"Setting RF device to EXMIMO\n"); #elif OAI_USRP rrh_mod.devs=oai_dv; rrh_mod.devs->type=USRP_B200_IF; LOG_I(RRH,"Setting RF device to USRP\n"); #elif OAI_BLADERF rrh_mod.devs=oai_dv; rrh_mod.devs->type=BLADERF_IF; LOG_I(RRH,"Setting RF device to BLADERF\n"); #else rrh_mod.devs=oai_dv; rrh_mod.devs->type=NONE_IF; LOG_I(RRH,"Setting RF interface to NONE_IF... \n"); #endif return rrh_mod; }
/* ---------------------------------------------------------------------------------------------- */ int main(int argc, char* argv[]) { unsigned long in, out, tot; char* device; char bufIn[20], bufOut[20], bufTot[20]; struct sigaction sig_struct; /* Signal fuer's Beenden */ sig_struct.sa_handler = sig_end_handler; sigemptyset(&sig_struct.sa_mask); sig_struct.sa_flags = 0; if (sigaction(SIGINT, &sig_struct, NULL) != 0) { perror("Fehler"); } if (argc != 2) { fprintf(stderr, "No device given. Exiting ...\n"); return 1; } device = argv[1]; init_netload(&data, device); for (;;) { get_current_netload(&data, &in, &out, &tot); format_with_thousandssep(bufIn, 20, (double)in, 2); format_with_thousandssep(bufOut, 20, (double)in, 2); format_with_thousandssep(bufTot, 20, (double)in, 2); printf("Current netload:\nIN : %s\nOUT: %s\nTOT: %s\nIP: %s\n", bufIn, bufOut, bufTot, get_ip_address(&data)); sleep(1); } return 0; }
/* TODO: redesign to avoid longjmp/setjmp. Several variables here have a volatile qualifier to silence warnings from gcc < 3.0. Remove the volatile qualifiers if longjmp/setjmp are removed. */ int main(int argc, char **argv, char **envp) { struct in_addr inetaddr; volatile int callmgr_sock = -1; char ttydev[PATH_MAX]; int pty_fd, tty_fd, gre_fd, rc; volatile pid_t parent_pid, child_pid; u_int16_t call_id, peer_call_id; char buf[128]; int pppdargc; char **pppdargv; char phonenrbuf[65]; /* maximum length of field plus one for the trailing * '\0' */ char * volatile phonenr = NULL; volatile int launchpppd = 1, debug = 0, nodaemon = 0; while(1){ /* structure with all recognised options for pptp */ static struct option long_options[] = { {"phone", 1, 0, 0}, {"nolaunchpppd", 0, 0, 0}, {"quirks", 1, 0, 0}, {"debug", 0, 0, 0}, {"sync", 0, 0, 0}, {"timeout", 1, 0, 0}, {"logstring", 1, 0, 0}, {"localbind", 1, 0, 0}, {"loglevel", 1, 0, 0}, {"nobuffer", 0, 0, 0}, {"idle-wait", 1, 0, 0}, {"max-echo-wait", 1, 0, 0}, {"version", 0, 0, 0}, {"nodaemon", 0, 0, 0}, {0, 0, 0, 0} }; int option_index = 0; int c; c = getopt_long (argc, argv, "", long_options, &option_index); if (c == -1) break; /* no more options */ switch (c) { case 0: if (option_index == 0) { /* --phone specified */ /* copy it to a buffer, as the argv's will be overwritten * by inststr() */ strncpy(phonenrbuf,optarg,sizeof(phonenrbuf)); phonenrbuf[sizeof(phonenrbuf) - 1] = '\0'; phonenr = phonenrbuf; } else if (option_index == 1) {/* --nolaunchpppd specified */ launchpppd = 0; } else if (option_index == 2) {/* --quirks specified */ if (set_quirk_index(find_quirk(optarg))) usage(argv[0]); } else if (option_index == 3) {/* --debug */ debug = 1; } else if (option_index == 4) {/* --sync specified */ syncppp = 1; } else if (option_index == 5) {/* --timeout */ float new_packet_timeout = atof(optarg); if (new_packet_timeout < 0.0099 || new_packet_timeout > 10) { fprintf(stderr, "Packet timeout %s (%f) out of range: " "should be between 0.01 and 10 seconds\n", optarg, new_packet_timeout); log("Packet timeout %s (%f) out of range: should be" "between 0.01 and 10 seconds", optarg, new_packet_timeout); exit(2); } else { packet_timeout_usecs = new_packet_timeout * 1000000; } } else if (option_index == 6) {/* --logstring */ log_string = strdup(optarg); } else if (option_index == 7) {/* --localbind */ if (inet_pton(AF_INET, optarg, (void *) &localbind) < 1) { fprintf(stderr, "Local bind address %s invalid\n", optarg); log("Local bind address %s invalid\n", optarg); exit(2); } } else if (option_index == 8) { /* --loglevel */ log_level = atoi(optarg); if (log_level < 0 || log_level > 2) usage(argv[0]); } else if (option_index == 9) { /* --nobuffer */ disable_buffer = 1; } else if (option_index == 10) { /* --idle-wait */ int x = atoi(optarg); if (x < 0) { fprintf(stderr, "--idle-wait must not be negative\n"); log("--idle-wait must not be negative\n"); exit(2); } else { idle_wait = x; } } else if (option_index == 11) { /* --max-echo-wait */ int x = atoi(optarg); if (x < 0) { fprintf(stderr, "--max-echo-wait must not be negative\n"); log("--max-echo-wait must not be negative\n"); exit(2); } else { max_echo_wait = x; } fprintf(stderr, "--max-echo-wait ignored, not yet implemented\n"); } else if (option_index == 12) { /* --version */ fprintf(stdout, "%s\n", version); exit(0); } else if (option_index == 13) {/* --nodaemon */ nodaemon = 1; } break; case '?': /* unrecognised option */ /* fall through */ default: usage(argv[0]); } if (c == -1) break; /* no more options for pptp */ } /* at least one argument is required */ if (argc <= optind) usage(argv[0]); /* Get IP address for the hostname in argv[1] */ inetaddr = get_ip_address(argv[optind]); optind++; /* Find the ppp options, extract phone number */ pppdargc = argc - optind; pppdargv = argv + optind; log("The synchronous pptp option is %sactivated\n", syncppp ? "" : "NOT "); /* Now we have the peer address, bind the GRE socket early, before starting pppd. This prevents the ICMP Unreachable bug documented in <1026868263.2855.67.camel@jander> */ gre_fd = pptp_gre_bind(inetaddr); if (gre_fd < 0) { close(callmgr_sock); fatal("Cannot bind GRE socket, aborting."); } /* Find an open pty/tty pair. */ if(launchpppd){ rc = openpty (&pty_fd, &tty_fd, ttydev, NULL, NULL); if (rc < 0) { close(callmgr_sock); fatal("Could not find free pty."); } #if defined(__linux__) /* * if we do not turn off echo now, then if pppd sleeps for any * length of time (DNS timeouts or whatever) the other end of the * connect may detect the link as looped. Other OSen may want this * as well, but for now linux gets it. */ { struct termios tios; tcgetattr(tty_fd, &tios); cfmakeraw(&tios); tcsetattr(tty_fd, TCSAFLUSH, &tios); } #endif /* fork and wait. */ signal(SIGUSR1, do_nothing); /* don't die */ signal(SIGCHLD, do_nothing); /* don't ignore SIGCHLD */ parent_pid = getpid(); switch (child_pid = fork()) { case -1: fatal("Could not fork pppd process"); case 0: /* I'm the child! */ close (tty_fd); signal(SIGUSR1, SIG_DFL); child_pid = getpid(); break; default: /* parent */ close (pty_fd); close (gre_fd); /* * There is still a very small race condition here. If a signal * occurs after signaled is checked but before pause is called, * things will hang. */ if (!signaled) { pause(); /* wait for the signal */ } if (signaled == SIGCHLD) fatal("Child process died"); launch_pppd(ttydev, pppdargc, pppdargv); /* launch pppd */ perror("Error"); fatal("Could not launch pppd"); } } else { /* ! launchpppd */ pty_fd = tty_fd = STDIN_FILENO; /* close unused file descriptor, that is redirected to the pty */ close(STDOUT_FILENO); child_pid = getpid(); parent_pid = 0; /* don't kill pppd */ } do { /* * Open connection to call manager (Launch call manager if necessary.) */ callmgr_sock = open_callmgr(inetaddr, phonenr, argc, argv, envp, pty_fd, gre_fd); /* Exchange PIDs, get call ID */ } while (get_call_id(callmgr_sock, parent_pid, child_pid, &call_id, &peer_call_id) < 0); /* Send signal to wake up pppd task */ if (launchpppd) { kill(parent_pid, SIGUSR1); sleep(2); /* become a daemon */ if (!(debug || nodaemon) && daemon(0, 0) != 0) { perror("daemon"); } } else { /* re-open stderr as /dev/null to release it */ file2fd("/dev/null", "wb", STDERR_FILENO); } snprintf(buf, sizeof(buf), "pptp: GRE-to-PPP gateway on %s", ttyname(tty_fd)); #ifdef PR_SET_NAME rc = prctl(PR_SET_NAME, "pptpgw", 0, 0, 0); if (rc != 0) perror("prctl"); #endif inststr(argc, argv, envp, buf); if (sigsetjmp(env, 1)!= 0) goto shutdown; signal(SIGINT, sighandler); signal(SIGTERM, sighandler); signal(SIGKILL, sighandler); signal(SIGCHLD, sighandler); signal(SIGUSR1, sigstats); /* Do GRE copy until close. */ pptp_gre_copy(call_id, peer_call_id, pty_fd, gre_fd); shutdown: /* on close, kill all. */ if(launchpppd) kill(parent_pid, SIGTERM); close(pty_fd); close(callmgr_sock); exit(0); }
int main(int argc, char **argv, char **envp) { struct in_addr inetaddr; int callmgr_sock = -1; char ptydev[PTYMAX], ttydev[TTYMAX]; int pty_fd = -1; int gre_fd = -1; static volatile pid_t child_pid; u_int16_t call_id, peer_call_id; #ifdef EMBED openlog(argv[0],LOG_PID,LOG_USER); #endif if (argc < 2) usage(argv[0]); /* Step 1: Get IP address for the hostname in argv[1] */ for (;;) { inetaddr = get_ip_address(argv[1]); if(inetaddr.s_addr != 0) break; sleep(RESPAWN_DELAY); } /* * open the GRE socket early so that we do not get * ENOPROTOOPT errors if the other end responds too * quickly to our initial connection */ gre_fd = socket(AF_INET, SOCK_RAW, PPTP_PROTO); if (gre_fd < 0) { pptp_error("socket: %s\n", strerror(errno)); sleep(RESPAWN_DELAY); exit(1); } for (;;) { /* Step 2: Open connection to call manager * (Launch call manager if necessary.) */ callmgr_sock = open_callmgr(inetaddr, argc,argv,envp); if(callmgr_sock < 0){ close(gre_fd); pptp_error("Could not open connection to call manager - terminating"); sleep(RESPAWN_DELAY); exit(1); } pptp_debug("callmgr opened - fd = %x", callmgr_sock); /* Step 5: Exchange PIDs, get call ID */ if (get_call_id(callmgr_sock, getpid(), &call_id, &peer_call_id) >= 0) break; close(callmgr_sock); } /* Step 3: Find an open pty/tty pair. */ pty_fd = getpseudotty(ttydev, ptydev); if (pty_fd < 0) { close(gre_fd); close(callmgr_sock); pptp_error("Could not find free pty."); sleep(RESPAWN_DELAY); exit(1); } pptp_debug("got a free ttydev"); /* Step 4: fork and wait. */ signal(SIGUSR1, do_nothing); /* don't die */ switch (child_pid = vfork()) { case -1: signal(SIGUSR1, SIG_DFL); pptp_debug("vfork failed %s", strerror(errno)); sleep(RESPAWN_DELAY); goto shutdown; case 0: /* I'm the child! */ // signal(SIGUSR1, SIG_DFL); pptp_debug("entered child"); pptp_debug("callids established.."); close(callmgr_sock); close(gre_fd); close(pty_fd); launch_pppd(ttydev, argc-2, argv+2); /* launch pppd */ sleep(RESPAWN_DELAY); exit(1); /* in case launch_pppd returns */ break; default: /* parent */ /* * There is still a very small race condition here. If a signal * occurs after signaled is checked but before pause is called, * things will hang. */ #if 0 if (!signaled) { pause(); /* wait for the signal */ } pptp_error("Error %s", strerror(errno)); #endif /*0*/ break; } #if 0 /* Step 5b: Send signal to wake up pppd task */ kill(parent_pid, SIGUSR1); sleep(2); #endif /*0*/ if (sigsetjmp(env, 1)!=0) goto shutdown; signal(SIGINT, sighandler); signal(SIGTERM, sighandler); signal(SIGKILL, sighandler); { char buf[128]; snprintf(buf, sizeof(buf), "pptp: GRE-to-PPP gateway on %s", ptydev); inststr(argc,argv,envp, buf); } /* Step 6: Do GRE copy until close. */ pptp_gre_copy(peer_call_id, call_id, pty_fd, gre_fd, inetaddr); shutdown: /* Make sure pppd exits as well */ if (child_pid > 0) kill(child_pid, SIGTERM); if (gre_fd != -1) close(gre_fd); if (pty_fd != -1) close(pty_fd); if (callmgr_sock != -1) close(callmgr_sock); exit(0); }
int main(int argc, char *argv[]) // _M1 { int client_waiting = 0; int waiting_client_ip = -1; int waiting_client_port = -1; int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; socklen_t addr_len; char s[INET6_ADDRSTRLEN]; /* _M1 Begin */ if (argc != 2) { fprintf(stderr,"usage: ServerUDP Port# \n"); exit(1); } /* _M1 End*/ memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4 hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, argv[1] /* _M1 MYPORT */, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("listener: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); while (1){ // _M2 printf("\n >>>> listener: waiting for a datagram...\n"); addr_len = sizeof their_addr; lab_3_request *request = (lab_3_request *)malloc(sizeof(lab_3_request)); if ((numbytes = recvfrom(sockfd, request, /*MAXBUFLEN*/sizeof(lab_3_request), 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } printf("Received raw bytes:\n"); displayBuffer((char *) request, numbytes); request_to_host_byte_order(request); printf("Bytes after endianness conversion:\n"); displayBuffer((char *)request, numbytes); printf("Received from client:\n"); printf("Magic number: %u\n", request->magic_number); printf("Group ID: %u\n", request->group_id); printf("Port Number: %u\n", request->port_number); printf("listener: got packet from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); printf("listener: packet is %d bytes long\n", numbytes); int error_code = get_error_code(request->group_id, request->port_number, request->magic_number); if(error_code) { lab_3_error_response *response = malloc(sizeof(lab_3_error_response)); response->magic_number = MAGIC_NUMBER; response->group_id = GROUP_ID; response->padding = PADDING; response->error_code = error_code; printf("Sending error response:\n"); displayBuffer((char *)response, ERROR_RESPONSE_SIZE); printf("Magic Number: %u\n", response->magic_number); printf("Group ID: %u\n", response->group_id); printf("Padding: %u\n", response->padding); printf("Error Code: %u\n", response->error_code); //TODO: To network byte order error_to_network_byte_order(response); sendto(sockfd, response, ERROR_RESPONSE_SIZE, 0, (struct sockaddr *)&their_addr, addr_len); } else if(client_waiting) { lab_3_client_waiting_response *response = malloc(sizeof(lab_3_client_waiting_response)); response->magic_number = MAGIC_NUMBER; response->group_id = GROUP_ID; response->ip_address = waiting_client_ip; response->port_number = waiting_client_port; printf("\nSending response to matched player:"); displayBuffer((char *)response, CLIENT_WAITING_RESPONSE_SIZE); printf("Magic Number: %u\n", response->magic_number); printf("Group ID: %u\n", response->group_id); printf("IP Address (in decimal): %u\n", response->ip_address); printf("Port Number: %u\n", response->port_number); //TODO: To network byte order client_waiting_response_to_network_byte_order(response); sendto(sockfd, response, CLIENT_WAITING_RESPONSE_SIZE, 0, (struct sockaddr *)&their_addr, addr_len); //Flush stored information client_waiting = 0; waiting_client_ip = -1; waiting_client_port = -1; } else { client_waiting = -1; //TODO: verify this correctly converts IP addresses waiting_client_ip = get_ip_address(&their_addr); waiting_client_port = request->port_number; lab_3_no_client_waiting_response *response = malloc(sizeof(lab_3_client_waiting_response)); response->magic_number = request->magic_number; response->group_id = request->group_id; response->port_number = request->port_number; printf("\nSending Response to new game host:"); displayBuffer((char *)response, NO_CLIENT_WAITING_RESPONSE_SIZE); printf("Magic Number: %u\n", response->magic_number); printf("Group ID: %u\n", response->group_id); printf("Port Number: %u\n", response->port_number); no_client_waiting_response_to_network_byte_order(response); sendto(sockfd, response, NO_CLIENT_WAITING_RESPONSE_SIZE, 0, (struct sockaddr *)&their_addr, addr_len); } } // _M2 close(sockfd); return 0; }
int main() { prog_init(); init_green(); init_blue(); init_red(); int open_file_status = read_map(); if (open_file_status == -1) { std::cout << "Open file failed! Exiting......" << std::endl; return -1; } //std::cout<<"step 1"<<std::endl; //set_fonts(); int i; //XSetForeground(dis, green_gc, green_col.pixel); sleep(1); XClearWindow(dis, win); XFlush(dis); XDrawRectangle(dis, win, green_gc, 10, 10, 580, 580); XDrawString(dis, win, blue_gc, 150, 300, welcomestring, strlen(welcomestring)); XFlush(dis); sleep(1); XClearWindow(dis, win); XDrawRectangle(dis, win, green_gc, 10, 10, 580, 580); XDrawString(dis, win, blue_gc, 20, 20, startingserver, strlen(startingserver)); XFlush(dis); get_ip_address(); //draw the initial position of the car ini_all_display(90, 90, 90); generate_route(); ini_all_display(90, 90, 90); facing_direction = DOWN_WARD; //to control UI //XSelectInput(dis, win, ExposureMask | KeyPressMask | ButtonPressMask); while (1) { int socketfd; // The socket descripter if (!connection) { std::cout << "Creating a socket..." << std::endl; socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol); if (socketfd == -1) { std::cout << "socket error!" << std::endl; } std::cout << "Binding socket..." << std::endl; // we use to make the setsockopt() function to make sure the port is not in use // by a previous execution of our code. (see man page for more information) int yes = 1; server_status = setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (int)); server_status = bind(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen); if (server_status == -1) { std::cout << "bind error! restart the program and check your IP address!" << std::endl; return -1; } std::cout << "Listening for connections..." << std::endl; server_status = listen(socketfd, 5); if (server_status == -1) { std::cout << "listen error" << std::endl; } connection = true; struct sockaddr_storage their_addr; socklen_t addr_size = sizeof (their_addr); new_sd = accept(socketfd, (struct sockaddr *) &their_addr, &addr_size); if (new_sd == -1) { std::cout << "listen error" << std::endl; connection = false; } else { std::cout << "Connection accepted. Using new socketfd : " << new_sd << std::endl; connection = true; } } int handshake = 0; while (connection) { std::cout << "Waiting to receive data..." << std::endl; ssize_t bytes_recieved; char incomming_data_buffer[1000]; //timeout starts struct timeval tv; tv.tv_sec = 10; /* x Seconds Timeout */ tv.tv_usec = 0; // Not initializing this can cause strange errors setsockopt(new_sd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof (struct timeval)); //timeout ends bytes_recieved = recv(new_sd, incomming_data_buffer, 1000, 0); if (bytes_recieved == 0) std::cout << "host shut down." << std::endl; if (bytes_recieved == -1) { std::cout << "Lost connection! Trying to re-establish connection..." << std::endl; connection = false; break; } std::cout << " bytes received :" << bytes_recieved << std::endl; incomming_data_buffer[bytes_recieved] = '\0'; std::cout << incomming_data_buffer << std::endl; //handshake if (handshake == 0) { if (strcmp(incomming_data_buffer, "requestHS") == 0) { std::cout << "Hand shake received, sending back handshake accepted" << std::endl; unsigned char handshakeindicator = 254; const unsigned char * hsmsg = &handshakeindicator; ssize_t bytes_sent; bytes_sent = send(new_sd, hsmsg, 1, 0); handshake = 1; continue; } else { std::cout << "handshake not received, waiting for handshake signal" << std::endl; continue; } } else { //get the received number,which indicates the status slavestatus = atoi(incomming_data_buffer); std::cout << "incoming data buffer is " << incomming_data_buffer << " and slave status is " << slavestatus << std::endl; } if (slavestatus == 250) { // done should_move = true; move_distance = 5; firsttime = false; } else if (slavestatus == 211) { //turn left std::cout << "waiting for turn left ack" << std::endl; turnleft_ack = true; } else if (slavestatus == 212) { //turn right std::cout << "waiting for turn right ack" << std::endl; turnright_ack = true; } else if (slavestatus == 232) { std::cout << "turned right" << std::endl; //facing for turn right if (facing_direction < 4) { facing_direction++; } else { facing_direction = DOWN_WARD; } move_distance = 55; should_move = true; avoid_right_turned = true; } else if (slavestatus == 231) { std::cout << "turned left" << std::endl; //facing for turn left if (facing_direction > 1) { facing_direction--; } else { facing_direction = RIGHT_WARD; } move_distance = 55; should_move = true; avoid_left_turned = true; } else if (slavestatus == 224) { should_move = true; move_distance = 5; avoid_A = true; } else if (slavestatus == 225) { //std::cout<<"got 225"<<std::endl; should_move = false; //move_distance = 15; avoid_B = true; } else if (slavestatus == 226) { //facing for turn left if (facing_direction > 1) { facing_direction--; } else { facing_direction = RIGHT_WARD; } move_distance = 55; should_move = true; avoid_B_DONE = true; } else if (slavestatus == 227) { should_move = true; move_distance = 5; //need to plus 110 steps here avoid_C = true; } else if (slavestatus == 228) { //facing for turn left if (facing_direction > 1) { facing_direction--; } else { facing_direction = RIGHT_WARD; } move_distance = 55; should_move = true; avoid_C_DONE = true; } else if (slavestatus == 229) { should_move = true; move_distance = 5; avoid_D = true; } else if (slavestatus == 230) { //facing for turn right if (facing_direction < 4) { facing_direction++; } else { facing_direction = DOWN_WARD; } move_distance = 55; should_move = true; avoid_D_DONE = true; firsttime = false; } else if (slavestatus == 234) { //std::cout<<"got 225"<<std::endl; should_move = false; //move_distance = 15; avoid_E = true; } else if (slavestatus == 235) { //facing for turn right if (facing_direction < 4) { facing_direction++; } else { facing_direction = DOWN_WARD; } move_distance = 55; should_move = true; avoid_E_DONE = true; } else if (slavestatus == 236) { should_move = true; move_distance = 5; // need to plus 110 steps avoid_F = true; } else if (slavestatus == 237) { //facing for turn right if (facing_direction < 4) { facing_direction++; } else { facing_direction = DOWN_WARD; } move_distance = 55; should_move = true; avoid_F_DONE = true; } else if (slavestatus == 238) { should_move = true; move_distance = 5; avoid_G = true; } else if (slavestatus == 239) { //facing for turn left if (facing_direction > 1) { facing_direction--; } else { facing_direction = RIGHT_WARD; } move_distance = 55; should_move = true; avoid_G_DONE = true; firsttime = false; } else if (slavestatus == 201) { //regular turn left //facing for turn left if (facing_direction > 1) { facing_direction--; } else { facing_direction = RIGHT_WARD; } move_distance = 0; should_move = true; reg_turnleft = true; firsttime = false; } else if (slavestatus == 202) { //regular turn right //facing for right turn if (facing_direction < 4) { facing_direction++; } else { facing_direction = DOWN_WARD; } move_distance = 0; should_move = true; reg_turnright = true; firsttime = false; } else { //slavestatus is not the number we want should_move = false; } if (should_move) { switch (facing_direction) { default: break; case UP_WARD: car_facing_up(x_current, y_current, (y_current - (move_distance))); y_current -= move_distance; break; case DOWN_WARD: car_facing_down(x_current, y_current, (y_current + (move_distance))); y_current += move_distance; break; case LEFT_WARD: car_facing_left(x_current, y_current, (x_current - (move_distance))); x_current -= move_distance; break; case RIGHT_WARD: car_facing_right(x_current, y_current, (x_current + (move_distance))); x_current += move_distance; break; } } std::cout << "sending back a message..." << std::endl; /*std::cout<<"Please type command (STR,LFT,RHT)"<<std::endl; std::cin>>cmdtocar; char msg[] = "CMD "; /std::cout << "Please type command (STR,LFT,RHT)" << std::endl; std::cin >> cmdtocar; strcat(msg, cmdtocar); strcat(msg, "\n");*/ int len; if (firsttime == false) { //vertical, go straight if (((x_current - 50) == en_route_x[point_times + 1])&& ((y_current - 50) != en_route_y[point_times + 1])) { cmd_number = 140; firsttime = true; } else if (((x_current - 50) != en_route_x[point_times + 1]) && ((y_current - 50) == en_route_y[point_times + 1])) { cmd_number = 140; firsttime = true; }//need to turn else if (((y_current - 50) == en_route_y[point_times + 1]) && ((x_current - 50) == en_route_x[point_times + 1])) { point_times++; if (point_times == route_points) { std::cout << "you have reached your destination" << std::endl; std::cout << "Please enter next destination" << std::endl; /* * * 2. ask for input * 3. add turn 180 degree * 4. modify the case below for turnings, and add a 180 degree turn function * 5. reset point_times++ */ //ask user input generate_route(); point_times = 1; } switch (facing_direction) { default: break; case UP_WARD: if ((en_route_x[point_times] < en_route_x[point_times + 1])) { cmd_number = 202; firsttime = true; //turn right } else if ((en_route_x[point_times] > en_route_x[point_times + 1])) { cmd_number = 201; firsttime = true; //turn left } else if (en_route_y[point_times] < en_route_y[point_times + 1]){ cmd_number = 203; firsttime = true; }else if (en_route_y[point_times] > en_route_y[point_times + 1]){ cmd_number = 140; firsttime = true; }else{ std::cout << "sth wrong 2" << std::endl; } break; case DOWN_WARD: if ((en_route_x[point_times] < en_route_x[point_times + 1])) { cmd_number = 201; firsttime = true; //turn left } else if ((en_route_x[point_times] > en_route_x[point_times + 1])) { cmd_number = 202; firsttime = true; //turn right } else if (en_route_y[point_times] < en_route_y[point_times + 1]){ cmd_number = 140; firsttime = true; }else if (en_route_y[point_times] > en_route_y[point_times + 1]){ cmd_number = 203; firsttime = true; } else { std::cout << "sth wrong 3" << std::endl; } break; case LEFT_WARD: if ((en_route_y[point_times] < en_route_y[point_times + 1])) { cmd_number = 201; firsttime = true; //turn left } else if ((en_route_y[point_times] > en_route_y[point_times + 1])) { cmd_number = 202; firsttime = true; //turn right } else if (en_route_x[point_times] > en_route_x[point_times + 1]){ cmd_number = 140; firsttime = true; }else if (en_route_x[point_times] < en_route_x[point_times + 1]){ cmd_number = 203; firsttime = true; } else { std::cout << "sth wrong 4" << std::endl; } break; case RIGHT_WARD: if ((en_route_y[point_times] > en_route_y[point_times + 1])) { cmd_number = 201; firsttime = true; //turn left } else if ((en_route_y[point_times] < en_route_y[point_times + 1])) { cmd_number = 202; firsttime = true; //turn right }else if (en_route_x[point_times] < en_route_x[point_times + 1]){ cmd_number = 140; firsttime = true; }else if (en_route_x[point_times] > en_route_x[point_times + 1]){ cmd_number = 203; firsttime = true; }else { std::cout << "sth wrong 5" << std::endl; } break; } } else { std::cout << "sth wrong 6" << std::endl; } } else if (turnright_ack == true) { cmd_number = 222; turnright_ack = false; } else if (turnleft_ack == true) { cmd_number = 221; turnleft_ack = false; } else if (avoid_right_turned == true) { cmd_number = 223; avoid_right_turned = false; } else if (avoid_left_turned == true) { cmd_number = 233; avoid_left_turned = false; } else if (avoid_A == true) { cmd_number = 224; avoid_A = false; } else if (avoid_B == true) { cmd_number = 225; avoid_B = false; } else if (avoid_B_DONE == true) { cmd_number = 226; avoid_B_DONE = false; } else if (avoid_C == true) { cmd_number = 227; avoid_C = false; } else if (avoid_C_DONE == true) { cmd_number = 228; avoid_C_DONE = false; } else if (avoid_D == true) { cmd_number = 229; avoid_D = false; } else if (avoid_D_DONE == true) { cmd_number = 230; avoid_D_DONE = false; } else if (avoid_E == true) { cmd_number = 234; avoid_E = false; } else if (avoid_E_DONE == true) { cmd_number = 235; avoid_E_DONE = false; } else if (avoid_F == true) { cmd_number = 236; avoid_F = false; } else if (avoid_F_DONE == true) { cmd_number = 237; avoid_F_DONE = false; } else if (avoid_G == true) { cmd_number = 238; avoid_G = false; } else if (avoid_G_DONE == true) { cmd_number = 239; avoid_G_DONE = false; } else if (reg_turnleft || reg_turnright) { //need condition cmd_number = 140; reg_turnleft = false; reg_turnright = false; } else { cmd_number = 253; } unsigned char test_byte_int = cmd_number; const unsigned char* test_byte = &test_byte_int; ssize_t bytes_sent; len = 1; bytes_sent = send(new_sd, test_byte, len, 0); int youshouldwork = test_byte_int; std::cout << "Msg sent was " << youshouldwork << std::endl; usleep(400000); } if (!connection) { std::cout << "Closing sockets..." << std::endl; //freeaddrinfo(host_info_list); close(new_sd); close(socketfd); std::cout << "server stopped, restarting......" << std::endl; firsttime = false; ini_all_display(90, 90, 90); x_current = 90; y_current = 90; } } return (0); }
int main(int argc, char** argv) { const uint8_t MAGIC_BYTE = 0x11; const uint8_t VERSION = 0x02; struct sockaddr_in saddr; int status; char hostname[255]; parse_options(argc, argv); if(gethostname(hostname, sizeof(hostname))) { perror("Infocast: gethostname"); exit(1); } int hlen = strlen(hostname) + 1; int len = 512; char* message = (char*)malloc(len); while(1) { unsigned char lanMacAddress[6]; unsigned char wifiMacAddress[6]; uint32_t ipLan, ipWLan; int8_t bat = (int8_t)(get_battery_info() * 100); uint8_t wifiStrength = get_wifi_quality(); uint8_t cpuTemp = get_cpu_temperature(); get_ip_address("eth0", ipLan, lanMacAddress); get_ip_address("wlan0", ipWLan, wifiMacAddress); char* start = message; *start = MAGIC_BYTE; start++; *start = VERSION; start++; WRITE(&ipLan, sizeof(ipLan)); WRITE(&ipWLan, sizeof(ipWLan)); WRITE(&bat, sizeof(bat)); WRITE(&cpuTemp, sizeof(cpuTemp)); WRITE(&wifiStrength, sizeof(wifiStrength)); WRITE(lanMacAddress, sizeof(lanMacAddress)); WRITE(wifiMacAddress, sizeof(wifiMacAddress)); memcpy(start, hostname, hlen); start += hlen; /* * We have to do this every iteration because we want see the Nao also * when a new interface becomes ready. For example eth0 gets an IP address * This should be no problem. Creating a socket is cheap. */ std::list<int> sockList = open_send_multicast_socket(saddr, multicast_ip.c_str(), multicast_port); for(std::list<int>::iterator it = sockList.begin(); it != sockList.end(); ++it) { int sock = *it; status = sendto(sock, message, start - message, 0, (struct sockaddr*)&saddr,sizeof(saddr)); close(sock); if(status < 0) perror("Infocast: sendto"); } sleep(5); } }