コード例 #1
0
ファイル: LWIPInterface.cpp プロジェクト: TomoYamanaka/mbed
void LWIP::add_dns_addr(struct netif *lwip_netif)
{
    // Check for existing dns address
    for (char numdns = 0; numdns < DNS_MAX_SERVERS; numdns++) {
        const ip_addr_t *dns_ip_addr = dns_getserver(numdns);
        if (!ip_addr_isany(dns_ip_addr)) {
            return;
        }
    }

    // Get preferred ip version
    const ip_addr_t *ip_addr = get_ip_addr(false, lwip_netif);
    u8_t addr_type = IPADDR_TYPE_ANY;

    // Add preferred ip version dns address to index 0
    if (ip_addr) {
        addr_type = get_ip_addr_type(ip_addr);
        add_dns_addr_to_dns_list_index(addr_type, 0);
    }

#if LWIP_IPV4 && LWIP_IPV6
    if (!ip_addr) {
        // Get address for any ip version
        ip_addr = get_ip_addr(true, lwip_netif);
        if (!ip_addr) {
            return;
        }
        addr_type = get_ip_addr_type(ip_addr);
        // Add the dns address to index 0
        add_dns_addr_to_dns_list_index(addr_type, 0);
    }

    if (addr_type == IPADDR_TYPE_V4) {
        // If ipv4 is preferred and ipv6 is available add ipv6 dns address to index 1
        ip_addr = get_ipv6_addr(lwip_netif);
    } else if (addr_type == IPADDR_TYPE_V6) {
        // If ipv6 is preferred and ipv4 is available add ipv4 dns address to index 1
        ip_addr = get_ipv4_addr(lwip_netif);
    } else {
        ip_addr = NULL;
    }

    if (ip_addr) {
        addr_type = get_ip_addr_type(ip_addr);
        add_dns_addr_to_dns_list_index(addr_type, 1);
    }
#endif
}
コード例 #2
0
ファイル: isns_client.c プロジェクト: imp/slist
/*
 * isns_init() needs to be call before all ISNS operations.
 * Save the isns_server & entity name.
 * Start esi_scn_thr to receive ESI & SCN messages
 */
int
isns_init(target_queue_t *q)
{
	char	*entity = NULL;

	if (q != NULL)
		mgmtq = q;

	if (isns_enabled() == False)
		return (0);

	/*
	 * get entity from the configuration if it set, alternatively
	 * get local hostname for entity usage. If environment variable
	 * ISCSITGT_ISNS_ENTITY is set it overrides all the other means
	 * of entity definition
	 */

	if (tgt_find_value_str(main_config, XML_ELEMENT_ISNS_ENTITY, &entity)) {
		(void) strlcpy(isns_args.entity, entity, MAXHOSTNAMELEN + 1);
		free(entity);
	} else {
		(void) gethostname(isns_args.entity, MAXHOSTNAMELEN);
	}

	/* Try environment variable - it overrides everything else */
	entity = getenv(ISCSITGT_ISNS_ENTITY);
	if (entity != NULL) {
		(void) strlcpy(isns_args.entity, entity, MAXHOSTNAMELEN + 1);
	}

	if ((strlen(isns_args.entity) == 0) ||
	    (get_ip_addr(isns_args.entity, &eid_ip) < 0)) {
		syslog(LOG_ERR, "isns_init: failed to get host name or host ip"
		    " address for ENTITY properties");
		return (-1);
	}

	isns_shutdown = False;

	(void) isns_populate_and_update_server_info(False);
	if (pthread_create(&scn_tid, NULL,
	    esi_scn_thr, (void *)&isns_args) !=
	    0) {
		syslog(LOG_ALERT, "isns_init failed to pthread_create");
		(void) pthread_kill(isns_tid, SIGKILL);
		return (-1);
	}

	if (pthread_create(&isns_tid, NULL, isns_server_connection_thr,
	    (void *)NULL) != 0) {
		syslog(LOG_ALERT,
		    "isns_init failed to create the "
		    "isns connection thr");
		return (-1);
	}

	isns_server_connection_thr_running = True;
	return (0);
}
コード例 #3
0
ファイル: print_eth_info.c プロジェクト: stettberger/i3status
/*
 * Combines ethernet IP addresses and speed (if requested) for displaying
 *
 */
void print_eth_info(const char *interface, const char *format_up, const char *format_down) {
        const char *walk;
        const char *ip_address = get_ip_addr(interface);

        if (ip_address == NULL) {
                printf("%s", color("#FF0000"));
                printf("%s", format_down);
                (void)printf("%s", endcolor());
                return;
        } else {
                printf("%s", color("#00FF00"));
        }

        for (walk = format_up; *walk != '\0'; walk++) {
                if (*walk != '%') {
                        putchar(*walk);
                        continue;
                }

                if (strncmp(walk+1, "ip", strlen("ip")) == 0) {
                        printf("%s", ip_address);
                        walk += strlen("ip");
                } else if (strncmp(walk+1, "speed", strlen("speed")) == 0) {
                        print_eth_speed(interface);
                        walk += strlen("speed");
                }
        }

        (void)printf("%s", endcolor());
}
コード例 #4
0
ファイル: LWIPStack.cpp プロジェクト: donatieng/mbed
const char *LWIP::get_ip_address()
{
    if (!default_interface) {
        return NULL;
    }

    const ip_addr_t *addr = get_ip_addr(true, &default_interface->netif);

    if (!addr) {
        return NULL;
    }
#if LWIP_IPV6
    if (IP_IS_V6(addr)) {
        return ip6addr_ntoa_r(ip_2_ip6(addr), ip_address, sizeof(ip_address));
    }
#endif
#if LWIP_IPV4
    if (IP_IS_V4(addr)) {
        return ip4addr_ntoa_r(ip_2_ip4(addr), ip_address, sizeof(ip_address));
    }
#endif
#if LWIP_IPV6 && LWIP_IPV4
    return NULL;
#endif
}
コード例 #5
0
ファイル: print_eth_info.c プロジェクト: Yuhta/i3status
/*
 * Combines ethernet IP addresses and speed (if requested) for displaying
 *
 */
void print_eth_info(yajl_gen json_gen, char *buffer, const char *interface, const char *format_up, const char *format_down) {
        const char *walk;
        const char *ip_address = get_ip_addr(interface);
        char *outwalk = buffer;

        INSTANCE(interface);

        if (ip_address == NULL) {
                START_COLOR("color_bad");
                outwalk += sprintf(outwalk, "%s", format_down);
                goto out;
        }

        START_COLOR("color_good");

        for (walk = format_up; *walk != '\0'; walk++) {
                if (*walk != '%') {
                        *(outwalk++) = *walk;
                        continue;
                }

                if (strncmp(walk+1, "ip", strlen("ip")) == 0) {
                        outwalk += sprintf(outwalk, "%s", ip_address);
                        walk += strlen("ip");
                } else if (strncmp(walk+1, "speed", strlen("speed")) == 0) {
                        outwalk += print_eth_speed(outwalk, interface);
                        walk += strlen("speed");
                }
        }

out:
        END_COLOR;
        OUTPUT_FULL_TEXT(buffer);
}
コード例 #6
0
ファイル: mod_ip.c プロジェクト: fifilyu/zsr
static void collect_record(module_t *mod) {
    if (!list_empty(&mod->record_list))
        list_del_init(&mod->record_list);

    // 只会保留最后一次查询结果
    get_ip_addr(&mod->record_list);
}
コード例 #7
0
ファイル: alt_iniche_dev.c プロジェクト: fjanssen/Car2X
int iniche_devices_init(
    int                         if_count)
{
    alt_iniche_dev              *p_dev;
    alt_iniche_dev              *p_dev_list_end;
    NET                         p_net;
    ip_addr                     ipaddr,
                                netmask,
                                gw;
    int                         use_dhcp;

    /* Get the InterNiche device list. */
    p_dev = (alt_iniche_dev *) (alt_iniche_dev_list.next);
    p_dev_list_end = (alt_iniche_dev *) (&(alt_iniche_dev_list.next));

    /* Initialize each InterNiche device. */
    while (p_dev != p_dev_list_end)
    {
        /* Initialize the InterNiche device data record. */
        p_dev->p_driver_data = p_dev;
        p_dev->if_num = if_count;
        p_dev->p_net = nets[p_dev->if_num];

        /* Perform device specific initialization. */
        (*(p_dev->init_func))(p_dev);

        /* Get the interface IP address. */
        p_net = p_dev->p_net;
                
        if (get_ip_addr(p_dev, &ipaddr, &netmask, &gw, &use_dhcp))
        {
#ifdef DHCP_CLIENT
            /* 
             * OR in the DHCP flag, if enabled. This will allow any
             * application-specific flag setting in get_ip_addr(), such 
             * as enabling AUTOIP, to occur 
             */
            if (use_dhcp) {
                p_net->n_flags |= NF_DHCPC;
            }
#endif
            p_net->n_ipaddr = ipaddr;
            p_net->snmask = netmask;
            p_net->n_defgw = gw;
#ifdef IP_MULTICAST
	    p_net->n_mcastlist = mcastlist;
#if defined (IGMP_V1) || defined (IGMP_V2)
            p_net->igmp_oper_mode = IGMP_MODE_DEFAULT;
#endif  /* IGMPv1 or IGMPv2 */
#endif  /* IP_MULTICAST */
        }

        /* Initialize next device. */
        if_count++;
        p_dev = (alt_iniche_dev *) p_dev->llist.next;
    }

    return (if_count);
}
コード例 #8
0
ファイル: dwmstatus.c プロジェクト: Donearm/dwmstatus
/* 
 * setup the status bar here
 */
int
status(int tostatusbar)
{
    char *status = NULL;
    char *avgs = NULL;
    char *time = NULL;
    char *batt = NULL;
    char *net = NULL;
    char *temp = NULL;
    char *ipaddr = NULL;
    char *net_device_up = NET_DEVICE_PRIMARY;
    time_t count60 = 0;
    time_t count10 = 0;

    if (!(dpy = XOpenDisplay(NULL)) && tostatusbar == 0) {
        fprintf(stderr, "dwmstatus: cannot open display.\n");
        return 1;
    }

    for (;;sleep(0)) {
        /* Update every minute */
        if (runevery(&count60, 60)) {
            free(time);

            time  = mktimes("%Y/%m/%d %H:%M", TIMEZONE);
        }
        /* Update every 10 seconds */
        if (runevery(&count10, 10)) {
            free(avgs);
            free(temp);
            free(batt);

            avgs   = loadavg();
            temp   = gettemperature(TEMP_SENSOR_PATH, TEMP_SENSOR_UNIT);
            batt   = getbattery(BATT_PATH);
            if(!temp) free(temp);
        }
        /* Update every second */
        net    = get_netusage(net_device_up);
        ipaddr = get_ip_addr(net_device_up);

        /* Format of display */
        status = smprintf("%s (%s) | %s [%s] T %s | %s",
                net, ipaddr, batt, avgs, temp, time);
        if(!ipaddr) free(ipaddr);
        free(net);

        if(tostatusbar == 0)
            setstatus(status);
        else
            puts(status);

        free(status);
    }
    return 0;
}
コード例 #9
0
ファイル: backdoor-client.c プロジェクト: ianlee/backdoor
/*--------------------------------------------------------------------------------------------------------------------
-- FUNCTION: process_user
-- 
-- DATE: 2014/09/06
-- 
-- REVISIONS: (Date and Description)
-- 
-- DESIGNER: Luke Tao, Ian Lee
-- 
-- PROGRAMMER: Luke Tao, Ian Lee
-- 
-- INTERFACE: void * process_user (void * arg)
-- 
-- RETURNS: 0, not important
-- 
-- NOTES: Takes in user input, encrypts commands and sends them.
----------------------------------------------------------------------------------------------------------------------*/
void * process_user (void * arg)
{
	struct client * client = (struct client *) arg;

	char buffer[BUF_LENGTH];
	int quit = FALSE;
	int password_entered = FALSE;
	
	//Initial Suppress Password Echoing	
	struct termios initial_rsettings, new_rsettings;
	tcgetattr(fileno(stdin), &initial_rsettings);
	new_rsettings = initial_rsettings;
	new_rsettings.c_lflag &= ~ECHO;

	
	while(!quit)
	{
		// First time iteration
		if(!password_entered)
		{

			printf("Enter a password: "******"\nEnter a command: ");
		strcpy(client->command, get_line(buffer, BUF_LENGTH, stdin));

		if(strcmp(client->command, "quit") == 0)
		{
			quit = TRUE;
		}
		memset(buffer, 0, sizeof(buffer));

		sprintf(buffer, "%s %d %s%s%s", client->password, SERVER_MODE, CMD_START, client->command, CMD_END);
		printf("Sending data: %s\n", buffer);
		//Encrypt the data

		send_packet(xor_cipher(buffer, strlen(buffer)), strlen(buffer), get_ip_addr(NETWORK_INT), client->server_host, client->dst_port);
		
		//clear buffer
		memset(client->command, 0, BUF_LENGTH);
		//sleep to allow for response before prompting for next command
		usleep(2500000);
	
	}
	return 0;
}
コード例 #10
0
ファイル: send_arp.C プロジェクト: miguelleitao/send_arp
int main ( int argc, char** argv ) {

  struct in_addr src_in_addr, targ_in_addr;
  struct arp_packet pkt;
  struct sockaddr sa;
  int sock;

  if ( argc != 5 ) die(usage) ;

  sock = socket( AF_INET, SOCK_PACKET, htons(ETH_P_RARP) ) ;
  if ( sock < 0 ){
    perror("socket");
    exit(1);
  }

  pkt.frame_type     = htons(ARP_FRAME_TYPE);
  pkt.hw_type        = htons(ETHER_HW_TYPE);
  pkt.prot_type      = htons(IP_PROTO_TYPE);
  pkt.hw_addr_size   = ETH_HW_ADDR_LEN;
  pkt.prot_addr_size = IP_ADDR_LEN;
  pkt.op             = htons(OP_ARP_REQUEST);

  get_hw_addr( pkt.targ_hw_addr, argv[4] );
  get_hw_addr( pkt.rcpt_hw_addr, argv[4] );
  get_hw_addr( pkt.src_hw_addr,  argv[2] );
  get_hw_addr( pkt.sndr_hw_addr, argv[2] );

  get_ip_addr( &src_in_addr,  argv[1] );
  get_ip_addr( &targ_in_addr, argv[3] );

  memcpy( pkt.sndr_ip_addr, &src_in_addr,  IP_ADDR_LEN );
  memcpy( pkt.rcpt_ip_addr, &targ_in_addr, IP_ADDR_LEN );

  bzero( pkt.padding, 18 );

  strcpy( sa.sa_data, DEFAULT_DEVICE ) ;
  if ( sendto( sock, &pkt,sizeof(pkt), 0, &sa,sizeof(sa) ) < 0 ){
    perror("sendto");
    exit(1);
  }
  exit(0);
  
} ; // main
コード例 #11
0
ファイル: tcp_send.c プロジェクト: jaredshowa/Heis
int main(){
    
    error_counter=0;
     x='M';
    a=1;
     b=2;
     get_ip_addr();
    tcp_send(x, a, b, ip_adresse);
    return 0;
}
コード例 #12
0
static char *nativeGetXAddrs(const char *interface)
{
	char pTmp[1024] = {0};
	char localAddr[32];
	get_ip_addr(localAddr, interface);
	sprintf(pTmp, "http://%s:8080/onvif/ipcamera", localAddr);

	char *str;
	set_field_string(&str, pTmp);
	return str;
}
コード例 #13
0
ファイル: new_connection.c プロジェクト: Bridouille/zappy
void		log_connection(t_net *sock, char *message)
{
  t_net		*tmp;
  char		*ip;

  if (sock && (tmp = sock->peer))
    {
      if ((ip = get_ip_addr(tmp)))
        server_log(WARNING, "%s %s:%d", message, ip, port_number(tmp));
      free(ip);
    }
}
コード例 #14
0
ファイル: softetherserver.c プロジェクト: HuangLeo/KeyServer
int main()
{
	get_ip_addr(ip);
	printf("The ip_addr in softether.c:%s\n", ip);

	download_cert(ip);

	read_cert(AllString);
	printf("The following is a certificate:\n%s\n",AllString);

	delete_account_in_data(ip);

	establish_socket_connect(ip,AllString);

	return 0;
}
コード例 #15
0
ファイル: common.c プロジェクト: kento/ibrdma
void write_log(char* log)
{
  int fd;
  char *ip;
  char *prefix;
  char logfile[1024];

  ip = get_ip_addr("ib0");
  prefix = getenv("SCR_PREFIX");
  //sprintf(logfile,"%s/transfer/%s.log", prefix, ip);

  //sprintf(logfile,"/g/g90/sato5/log");
  fd = open("~/log",  O_WRONLY |O_APPEND| O_CREAT, 0660);
  write(fd, log, strlen(log));
  close(fd);
}
コード例 #16
0
ファイル: tcp.c プロジェクト: swathikirankumar/CN
int tcp_connect(char* hostname, char* port) {
    char* ip;
    int csock;
    int rv;
    struct addrinfo hints, *si, *p;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ((rv = getaddrinfo(hostname, port, &hints, &si)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return -1;
    }

    // loop through all the results and connect to the first we can
    for(p = si; p != NULL; p = p->ai_next) {
        if ((csock = socket(p->ai_family, p->ai_socktype,
                            p->ai_protocol)) == -1) {
            perror("socket");
            continue;
        }

        if (connect(csock, p->ai_addr, p->ai_addrlen) == -1) {
            close(csock);
            perror("client: connect");
            continue;
        }

        break;
    }

    if (p == NULL) {
        fprintf(stderr, "client: failed to connect\n");
        return -1;
    }

    ip = get_ip_addr(p);
    printf("client: connecting to %s ...\n", ip);
    free(ip);

    freeaddrinfo(si); // all done with this structure

    return csock;
}
コード例 #17
0
ファイル: scr_rdma_transfer_send.c プロジェクト: kento/ibrdma
int RDMA_transfer_init(void) 
{
  char *ip;
  char *prefix;
  char tfnfile[1024];
  int fd;
  char tfn[16];
  /*TODO: remove hard cored arg*/
  ip = get_ip_addr("ib0");
  prefix = getenv("SCR_PREFIX");
  sprintf(tfnfile,"%s/transfer/%s", prefix, ip);
  fd = open(tfnfile, O_RDONLY);
  read(fd, tfn, 16);
  close(fd);
  rdma_param.host = tfn;
  RDMA_Active_Init(&rdma_comm, &rdma_param);
  return 0;
}
コード例 #18
0
ファイル: scr_rdma_transfer_send.c プロジェクト: kento/ibrdma
int get_tag(void)
{
  char *ip;
  int tag = 0;
  int i;
  /*TODO: Remove hard cored arg*/
  ip = get_ip_addr("ib0");
  /*use last three ip octet for the message tag.
    Fisrt octet is passed.
  */
  atoi(strtok(ip, "."));
  tag = atoi(strtok(NULL, "."));
  for (i = 0; i < 2; i++) {
    tag = tag * 1000;
    tag = tag + atoi(strtok(NULL, "."));
  }
  return tag;
}
コード例 #19
0
ファイル: sr_arpcache.c プロジェクト: carterdy/csc458
/*
  Send a host unreachable ICMP to the given source address
*/
void send_echo_reply(uint8_t source_addr, uint8_t *packet, struct sr_instance *sr){
  
  /*Allocate a buffer to hold the packet*/
  uint8_t *buf = malloc(sizeof(sr_ethernet_hdr_t) + sizeof(sr_ip_hdr_t) + sizeof(sr_icmp_hdr_t));
  
  /*Create and send the host unreachable ICMP TO source, telling them that dest was unreachable*/
  /*First have to create the ICMP packet*/
  sr_icmp_t3_hdr_t *icmp_packet = (sr_icmp_hdr_t *)(buf + sizeof(sr_ip_hdr_t) + sizeof(sr_ethernet_hdr_t));
  icmp_packet->icmp_type = 1;
  icmp_packet->icmp_code = 1;
  icmp_packet->icmp_sum = 0;
  icmp_packet->icmp_sum = cksum((const void *)(icmp_packet.icmp_type + icmp_packet.icmp_code), 2);
  print_hdr_icmp(icmp_packet);
  /*Have to craft data.  Data will be the original packet header plus the first 8 bytes of the packet content.*/
  memcpy(icmp_packet->data, packet, ICMP_DATA_SIZE);
  
  /*Now have to form the ip packet to encase the icmp content*/
  sr_ip_hdr_t *ip_packet = (sr_ip_hdr_t *)(buf + sizeof(sr_ethernet_hdr_t));
  ip_packet->ip_p = 1;
  ip_packet->ip_tos;            /* type of service */
  ip_packet->ip_len;            /* total length */
  ip_packet->ip_id;         /* identification */
  ip_packet->ip_off;            /* fragment offset field */
  ip_packet->ip_ttl;            /* time to live */
  ip_packet->ip_p = 1;          /* protocol */
  ip_packet->ip_sum;            /* checksum */
  ip_packet->ip_src = sr->if_list[0]->ip;  /*Assign the packet source to one of the router's interfaces*/
  ip_packet->ip_dst = get_ip_addr(packet);  /*set the packet destination to the original source IP*/
  print_hdr_ip(ip_packet);
  memcpy((void *)arp_packet->ar_sha, (void *)sender_eth, ETHER_ADDR_LEN);
  /*Now make an ethernet frame to wrap the IP packet with the ICMP packet*/
  sr_ethernet_hdr_t *ether_packet = (sr_ethernet_hdr_t *)(buf);
  ether_packet->ether_dhost = source_addr;  /*Set ethernet destination*/
  ether_packet->ether_shost = sr->if_list[0]->addr;  /*Set ethernet source*/
  ether_packet->ether_type = sr_ethertype.ethertype_ip;
  print_hdr_eth(ether_packet);
  print_hdr_icmp(uint8_t *buf);
  /*Now send off the packet*/
  int size = 32+20+8+28; /*Size of the packet. Ether header = 32, ip header = 20, ICMP header = 8, ICMP data = 28.*/
  sr_send_packet(sr, buf, size, sr->if_list);
  

}
コード例 #20
0
int main()
{

    int send_sock,listen_sock;
    struct sockaddr_in listen_addr, send_addr, client_addr;
    struct hostent *host;
    char *ip_addr1; 

    char recv_data[256];
    char send_data[256];
    char message[256];
    int addr_len, bytes_read;

    int i,j,k; 
    char recv_msg[256];
    char msg_list[5][128]; 
    char comp_msg[16]; 
    char mn_fl_ip_addr[16];
    char ap_ip_addr[16];
    char ap_name[20];
    char ap_tunnel_ip[20];
    char ap_tunnel_ifc[20];
    char net_mask[20];

    struct pollfd my_sock_fd[2]; 
    int poll_result , optval;

    optval = 1; 

    //###############################
    //# Declaring AP Listen Socket	#
    //###############################

    if ((listen_sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("socket");
        exit(1);
    }

    ip_addr1 = "0"; 
    listen_addr.sin_family = AF_INET;
    listen_addr.sin_port = htons(9001);
    listen_addr.sin_addr.s_addr = inet_addr(ip_addr1);
    bzero(&(listen_addr.sin_zero),8);

    if((setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, 
            &optval, sizeof optval)) == -1)
    {
        perror("Socket setopt Error");
        exit(1);
    }

    if (bind(listen_sock,(struct sockaddr *)&listen_addr, sizeof(struct sockaddr)) == -1)
    {
        perror("BindError");
        exit(1);
    }

    my_sock_fd[0].fd = listen_sock; 
    my_sock_fd[0].events = POLLIN;

    //##########################
    //# Declaring Send Socket  #
    //##########################

    if ((send_sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
    {
        perror("SocketError");
        exit(1);
    }

    send_addr.sin_family = AF_INET;
    send_addr.sin_port = htons(9002);
    //send_addr.sin_addr = *((struct in_addr *)host->h_addr);

    bzero(&(send_addr.sin_zero),8);


    addr_len = sizeof(struct sockaddr);

    #ifdef DEBUG 
    	printf("\nGW Waiting for SWITCH-ROUTE on port 9001\n");
    #endif

    fflush(stdout);
    while (1)
    {
        while ((poll_result = poll(my_sock_fd, 1, -1)) <= 0)
        {
            if (poll_result < 0)
            {
                perror("Poll Error");
                exit(1);
            }
        }


        if (my_sock_fd[0].revents & POLLIN == 1)
        {
            bytes_read = recvfrom(listen_sock,recv_data,256,0,
                (struct sockaddr *)&client_addr, &addr_len);
              
            strcpy(ap_ip_addr , inet_ntoa(client_addr.sin_addr));

            recv_data[bytes_read] = '\0'; 

	    #ifdef DEBUG 
           	 printf("Received Data is :%s\n", recv_data);
  	    #endif

            fflush(stdout);


            j=0;
            k=0;
            for (i=0;i<=bytes_read;i++)
            {
                if (((recv_data[i] == ';') || (recv_data[i] == '\0')) && (k<4))
                {
                    recv_msg[j] = '\0'; 
                    strcpy(msg_list[k],recv_msg);
                    k++; 
                    j = 0; 
                }
                else 
                {
                    recv_msg[j] = recv_data[i];
                    j++;
                }
            }

            strcpy(msg_list[k],"NULL");
            k=0;
	    #ifdef DEBUG
                while ((k<4) && (strcmp(msg_list[k],"NULL")))
                {
                    printf("Messge %d is %s \n",k, msg_list[k]);
                    k++;
                }
	     #endif

            strcpy(mn_fl_ip_addr,msg_list[1]);
            strcpy(ap_name,msg_list[2]);

//            printf("Adding Route to MN IP Address\n");
            

    //###########################################
    //# Declaring MN IP address as host address
    //# to send message to
    //###########################################
    //
            host= (struct hostent *)gethostbyname((char *)ap_ip_addr);

            send_addr.sin_addr = *((struct in_addr *)host->h_addr);

    //###########################################
    //# Put in function call to get AP IP Addr  #
    //# and AP MAC Addrfrom the AP name given   #
    //# as message                              #
    //###########################################
            strcpy(ap_tunnel_ifc, ap_name); 
            strcpy(ap_tunnel_ip, get_ip_addr(ap_tunnel_ifc, ap_tunnel_ip, sizeof(ap_tunnel_ip)));
            strcpy(net_mask,"255.255.255.255"); 

            #ifdef DEBUG 
                printf("Deleting Old Route to MN \n");
                printf("Adding New Route to MN \n");
	    #endif

            route_del(mn_fl_ip_addr, net_mask, ap_tunnel_ifc); 
            route_add(mn_fl_ip_addr, net_mask, ap_tunnel_ip, ap_tunnel_ifc); 
            #ifdef DEBUG 
                printf("AP Name is %s \n",ap_name);
	    #endif

            sprintf (message, "SWITCH-ROUTE-OK;%s;%s",mn_fl_ip_addr,ap_name);

            strcpy(send_data,message); 

            strcpy(comp_msg ,"SWITCH-ROUTE"); 

            if (strcmp(msg_list[0],comp_msg)== 0)
            {
	       	#ifdef DEBUG 
               	    printf("Sending Message : %s \n",send_data); 
	    	#endif
                sendto(send_sock, send_data, strlen(send_data), 0,
                (struct sockaddr *)&send_addr, sizeof(struct sockaddr));
            }
        }     
    }

}
コード例 #21
0
ファイル: wiretap.c プロジェクト: supunkamburugamuve/wiretap
/*
    This is the callback function which will be called by pcap for each packet 
    found in the given dump. Inside this function, we parse Ethernet, IP, ARP,
    TCP, UDP and ICMP headers and store statistics.
*/
void callback_handler(u_char *user, const struct pcap_pkthdr *pcap_hdr, const u_char *packet) {
    int pkt_len = (int)pcap_hdr->len;
    // if this is the first packet we read, store the dump start time
    if (pkt_cnt == 0) {
        start_ts = pcap_hdr->ts;
        smallest = pkt_len;
        largest = pkt_len;
    } else {
        // check whether the current packet is the smallest or largest
        if (pkt_len < smallest)
            smallest = pkt_len;
        if (pkt_len > largest)
            largest = pkt_len;
    }    
    tot_size += pkt_len;
    pkt_cnt++;
    // assign each packet to end time as we don't know which one is the last
    end_ts = pcap_hdr->ts;

    // structures for parsing Ethernet, IP, ARP, TCP, UDP and ICMP headers
    const struct ether_header* eth_hdr;
    const struct ip* ip_hdr;
    const struct arpheader* arp_hdr;
    const struct tcphdr* tcp_hdr;
    const struct udphdr* udp_hdr;
    struct icmp* icmp_hdr;
    char src_ip[INET_ADDRSTRLEN];
    char dst_ip[INET_ADDRSTRLEN];

    // create ethernet header
    eth_hdr = (struct ether_header*)packet;
    // capture source mac address and destination mac address
    char *eth_src_addr = malloc(sizeof(char) * ETHER_ADDR_LEN);
    char *eth_dst_addr = malloc(sizeof(char) * ETHER_ADDR_LEN);
    get_eth_addr(eth_src_addr, (u_char*)eth_hdr->ether_shost);
    get_eth_addr(eth_dst_addr, (u_char*)eth_hdr->ether_dhost);   
    // add captured ethernet addresses into our maps to print later
    add_to_map(&src_eth_info.info_map, eth_src_addr);
    src_eth_info.pkt_count++;
    add_to_map(&dst_eth_info.info_map, eth_dst_addr);
    dst_eth_info.pkt_count++;

    char nw_prot[18];
    // check ethernet header type and get IP, ARP headers
    if (ntohs(eth_hdr->ether_type) == ETHERTYPE_IP) {
        strcpy(nw_prot, "IP");
        // create ip header
        ip_hdr = (struct ip*)(packet + sizeof(struct ether_header));
        // ignore ipv6
        if (ip_hdr->ip_v == 0x6) {
            return;
        }
        // store TTL info
        add_to_int_map(&ttl_info.info_map, ip_hdr->ip_ttl);
        ttl_info.pkt_count++;

        // get source and destination ip addresses
        inet_ntop(AF_INET, &(ip_hdr->ip_src), src_ip, INET_ADDRSTRLEN);
        inet_ntop(AF_INET, &(ip_hdr->ip_dst), dst_ip, INET_ADDRSTRLEN);
        // add captured IP addresses into our maps to print later
        add_to_map(&src_ip_info.info_map, src_ip);
        src_ip_info.pkt_count++;
        add_to_map(&dst_ip_info.info_map, dst_ip);
        dst_ip_info.pkt_count++;

        char trns_prot[10];
        if (ip_hdr->ip_p == IPPROTO_TCP) {
            strcpy(trns_prot, "TCP");
            tcp_hdr = (struct tcphdr*)(packet + sizeof(struct ether_header) + sizeof(struct ip));
            // add TCP source and destination ports into out maps
            add_to_int_map(&src_tcp_ports_info.info_map, ntohs(tcp_hdr->th_sport));
            src_tcp_ports_info.pkt_count++;
            add_to_int_map(&dst_tcp_ports_info.info_map, ntohs(tcp_hdr->th_dport));
            dst_tcp_ports_info.pkt_count++;

            char flag_key[3 * 6];
            process_tcp_flags(flag_key, tcp_hdr->th_flags);
            // add flags into our maps to print later
            add_to_map(&tcp_flag_info.info_map, flag_key);
            tcp_flag_info.pkt_count++;

            // read options
            if (tcp_hdr->th_off * 4 > 20) {
                int end = 0;
                int off = 0;
                int one = 0;
                char opt1[5], opt2[5];
                while (!end) {
                    char *p = (char*)(packet + sizeof(struct ether_header) + sizeof(struct ip) + sizeof(struct tcphdr) + off);
                    // if we encounter 0 that means end of options
                    if (p[0] == 0) {
                        end = 1;
                    } else {
                        if (p[0] != 1) {
                            sprintf(opt1, "%#.2x", (int)p[0]);
                            add_to_map(&tcp_opt_info.info_map, opt1);
                            off += (int)p[1];
                        } else {
                            off += 1;
                            if (!one) {
                                sprintf(opt2, "%#.2x", (int)p[0]);
                                add_to_map(&tcp_opt_info.info_map, opt2);
                            }
                            one = 1;
                        }
                        if (off >= (tcp_hdr->th_off * 4 - 20)) {
                            end = 1;
                        }
                    }
                }
            }
            tcp_opt_info.pkt_count++;
        } else if (ip_hdr->ip_p == IPPROTO_UDP) {
            strcpy(trns_prot, "UDP");
            udp_hdr = (struct udphdr*)(packet + sizeof(struct ether_header) + sizeof(struct ip));
            // add UDP source and destination ports into out maps
            add_to_int_map(&src_udp_ports_info.info_map, ntohs(udp_hdr->uh_sport));
            src_udp_ports_info.pkt_count++;
            add_to_int_map(&dst_udp_ports_info.info_map, ntohs(udp_hdr->uh_dport));
            dst_udp_ports_info.pkt_count++;
        } else if (ip_hdr->ip_p == IPPROTO_ICMP) {
            strcpy(trns_prot, "ICMP");
            icmp_hdr = (struct icmp*)(packet + sizeof(struct ether_header) + sizeof(struct ip));
            // add captured IP addresses into our maps to print later
            add_to_map(&icmp_src_ip_info.info_map, src_ip);
            icmp_src_ip_info.pkt_count++;
            add_to_map(&icmp_dst_ip_info.info_map, dst_ip);
            icmp_dst_ip_info.pkt_count++;

            // add ICMP type and code into our maps
            add_to_int_map(&icmp_type_info.info_map, (int)(icmp_hdr->icmp_type));
            icmp_type_info.pkt_count++;
            add_to_int_map(&icmp_code_info.info_map, (int)(icmp_hdr->icmp_code));
            icmp_code_info.pkt_count++;

            char icmp_cat[20];
            process_icmp_response((int)(icmp_hdr->icmp_type), (int)(icmp_hdr->icmp_code), icmp_cat);
            add_to_map(&icmp_cat_info.info_map, icmp_cat);
            icmp_cat_info.pkt_count++;
        } else {
            // we only have to store the protocol number here
            sprintf(trns_prot, "%#.2x", ip_hdr->ip_p);
        }
        // add transport layer protocol info into map
        add_to_map(&trns_prot_info.info_map, trns_prot);
        trns_prot_info.pkt_count++;
    } else if (ntohs(eth_hdr->ether_type) == ETHERTYPE_ARP) {
        strcpy(nw_prot, "ARP");
        arp_hdr = (struct arpheader*)(packet + sizeof(struct ether_header));
        // buffer for arp key in <mac> / <ip> format. Ex : 00:13:72:89:fd:1f / 129.79.245.139
        char *buf = malloc(sizeof(char) * (ETHER_ADDR_LEN + 5 + INET_ADDRSTRLEN));
        // get arp source mac
        char *arp_src_mac = malloc(sizeof(char) * ETHER_ADDR_LEN);
        get_eth_addr(arp_src_mac, (u_char*)arp_hdr->__ar_sha);
        strcat(buf, arp_src_mac);
        strcat(buf, " / ");
        // get arp source ip
        char *arp_src_ip = malloc(sizeof(char) * INET_ADDRSTRLEN);
        get_ip_addr(arp_src_ip, (u_char*)arp_hdr->__ar_sip);
        strcat(buf, arp_src_ip);
        // store ARP info
        add_to_map(&arp_info.info_map, buf);
        arp_info.pkt_count++;
    } else {
        // 'type' field in ethernet frames can be used for either the protocol or the
        // length of the packet. If it is for protocol, it should be at least 0x0600
        if (ntohs(eth_hdr->ether_type) < 0x0600)
            sprintf(nw_prot, "length = %#.4x", ntohs(eth_hdr->ether_type));
        else
            // we only have to store the protocol number here
            // (ntohs(eth_hdr->ether_type) == ETHERTYPE_IPV6) case will also come here
            // it will just be count as a different protocol
            sprintf(nw_prot, "%#.4x", ntohs(eth_hdr->ether_type));
    }
    // add network protocol info into map
    add_to_map(&nw_prot_info.info_map, nw_prot);
    nw_prot_info.pkt_count++;
}
コード例 #22
0
int main(int argc, char **argv)
{
	FILE *fp;
	char *line = NULL;
	char ip_addr[BUFSIZE];
	char *my_ip_addr;
	char buf[BUFSIZE];
	int port, range, rate;
	int line_length, message_size;
	int sockfd;
	double heart_rate;
	struct sockaddr_in server_addr;
	struct hostent *server;

	my_ip_addr = get_ip_addr();
	printf("My ip addr is: %s\n", my_ip_addr);

	/* READING COMMAND LINE ARGUMENTS */
	if (argc != 2) {
		fprintf(stderr, "Error. Usage: ./set_rate <rate>. Exiting.\n");
		exit(1);
	}
	
	rate = atoi(argv[1]);
	if (rate < 1 || rate > 5) {
		fprintf(stderr, "Error. Rate must be between 0 and 5. You supplied %d. Exiting.\n", rate);
		exit(1);
	}
	/* FINISHED READING COMMAND LINE ARGUMENTS */


	/* READ INPUT FILE */
	fp = fopen("config_file", "r");
	if (fp == NULL) {
		fprintf(stderr, "Error opening config file with name 'config_file'. Exiting.\n");
		exit(1);
	}
	printf("Reading input file...\n");
	while (getline(&line, &line_length, fp) > 0) {
		if (strstr(line, "host_ip") != NULL) {
			sscanf(line, "host_ip: %s\n", ip_addr);
		} else if (strstr(line, "port") != NULL) {
			sscanf(line, "port: %d\n", &port);
		}
	}
	fclose(fp);
	/* FINISH READING INPUT FILE */

	printf("Connecting to: %s:%d\n", ip_addr, port, rate, range);

	/* SETUP SOCKET COMMUNICATIONS */
	server = gethostbyname(ip_addr);
	socklen_t len = sizeof(server_addr);	

	//Set up datagram socket communication with ARPA Internet protocol 
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	bzero((char *)&server_addr, sizeof(server_addr));	
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(ip_addr);
	server_addr.sin_port = htons(port);
	/* FINISH SETUP SOCKET COMMUNICATIONS */

	/* SEND HEART RATE TO SERVER */
	sprintf(buf, "IP: %s new_rate: %d", my_ip_addr, rate);
	printf("Sending message '%s' to server...\n", buf);

	if (sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, len) < 0) {
		fprintf(stderr, "Failed to send.\n");
		exit (1);
	}

	return 0;
} 
コード例 #23
0
int WireNetworkInit()
{
	int ret = -1;
	int nDhcpFlag = -1;
	SYS_INFO sysInfo;
	NET_PARAM netParam;
	char ip[16];
	char mac_addr[32] = {0};
	char buffer_cache[128] ={0};
	
	ret = getNetParam(&netParam);
	if (ret < 0)
	{
		return -1;
	}
	
	// 自动生成多播地址
	generateMultiAddr(netParam.byMultiAddr);
	
	ifconfig_up_down(ETH_WIRE_DEV, "down");
	
	memset(mac_addr, 0, 32);
	if (get_net_phyaddr_ext(ETH_WIRE_DEV, mac_addr) == 0)
	{
		if (strcmp(netParam.strPhyAddr, mac_addr) != 0)
		{
			sprintf(mac_addr, "%02x:%02x:%02x:%02x:%02x:%02x", netParam.strPhyAddr[0], netParam.strPhyAddr[1], netParam.strPhyAddr[2], netParam.strPhyAddr[3], netParam.strPhyAddr[4], netParam.strPhyAddr[5]);
			ret = set_net_phyaddr(ETH_WIRE_DEV, mac_addr);
			printf("set_net_phyaddr: (WIRE: %s) %d\n", mac_addr, ret);
		}
	}
	
	ifconfig_up_down(ETH_WIRE_DEV, "up");

	if (netParam.nDhcpOnFlag == 1)
	{
		getSysInfoParam(&sysInfo);
		nDhcpFlag = dhcp_setup(ETH_WIRE_DEV, sysInfo.strDeviceName);
	}
	else
	{
		nDhcpFlag = -1;
	}

	memset(ip, 0, 16);
	ret = get_ip_addr(ETH_WIRE_DEV, ip);

	printf("dhcp_setup(WIRE): %d %s\n", nDhcpFlag, ip);

	if (nDhcpFlag != 0 || strlen(ip)<=0 || netParam.nDhcpOnFlag==0)
	{
		// Add the code by lvjh, 2008-03-22
		unsigned int add1 = 0;
		unsigned int add2 = 0;
		unsigned int add3 = 0;
		unsigned int add4 = 0;

		unsigned int add5 = 0;
		unsigned int add6 = 0;
		unsigned int add7 = 0;
		unsigned int add8 = 0;
			
		printf("DVS IP(WIRE): %s\n", netParam.byServerIp);


	#if 0
		if (set_ip_addr(ETH_WIRE_DEV, netParam.byServerIp) < 0)
		{
			printf("set_ip_addr(%s) Failed!\n", netParam.byServerIp);

			set_ip_addr(ETH_WIRE_DEV, DEFAULT_WIRE_IP);
			set_mask_addr(ETH_WIRE_DEV, DEFAULT_WIRE_MASK);
			//set_gateway_addr(DEFAULT_WIRE_GATEWAY);
			set_gateway_addr_ext(ETH_WIRE_DEV, DEFAULT_WIRE_GATEWAY);
			//return -1;
		}
	#endif
	

		sprintf(buffer_cache, "%s %s %s", "ifconfig",  ETH_WIRE_DEV, netParam.byServerIp);
		system(buffer_cache);

		if (set_mask_addr(ETH_WIRE_DEV, netParam.byServerMask) < 0)
		{
    	   	printf("set_mask_addr(%s) Failed!\n", netParam.byServerMask);
	
			set_mask_addr(ETH_WIRE_DEV, DEFAULT_WIRE_MASK);
			//set_gateway_addr(DEFAULT_WIRE_GATEWAY);
			set_gateway_addr_ext(ETH_WIRE_DEV, DEFAULT_WIRE_GATEWAY);
			//return -1;
		}

		//printf("Old GateWay: %s\n", netParam.byGateway);
		//sscanf(netParam.byServerIp, "%d.%d.%d.%d", &add1, &add2, &add3, &add4);
		//sscanf(netParam.byGateway, "%d.%d.%d.%d", &add5, &add6, &add7, &add8);
		//sprintf(netParam.byGateway, "%d.%d.%d.%d", add1, add2, add3, add8);
		//printf("New GateWay: %s\n", netParam.byGateway);
			
		//if (set_gateway_addr(netParam.byGateway) < 0)
		if (set_gateway_addr_ext(ETH_WIRE_DEV, netParam.byGateway) < 0)
		{
			printf("set_gateway_addr(%s) Failed!\n", netParam.byGateway);
			//set_gateway_addr(DEFAULT_WIRE_GATEWAY);
			set_gateway_addr_ext(ETH_WIRE_DEV, DEFAULT_WIRE_GATEWAY);
			//return -1;
		}
	}

	// DNS
	if (netParam.nDhcpOnFlag == 1)
	{
		char localIP[16];
		char gateway[16];
		
		memset(localIP, 0, 16);
		memset(gateway, 0, 16);

		//ret = get_gateway_addr(gateway);
		ret = get_gateway_addr_ext(ETH_WIRE_DEV, gateway);
		if (ret == 0)
		{
			printf("GateWay(WIRE): %s\n", gateway);

			set_dns_addr(gateway);
			
			strcpy(netParam.byGateway, gateway);
			strcpy(netParam.byDnsAddr, gateway);
		}
		ret = get_ip_addr(ETH_WIRE_DEV, localIP);
		if (ret == 0)
		{
			printf("DHCP: get_ip_addr: %s\n", localIP);
			strcpy(netParam.byServerIp, localIP);
		}
		printf("DHCP: %s %s\n", ETH_WIRE_DEV, localIP);
	
		setNetParam(&netParam);
	}
	else
	{
		set_dns_addr(netParam.byGateway);
	}
	
	return 0;
}
コード例 #24
0
ファイル: arp_spoofer.c プロジェクト: jotsb/Android-NDK
int main(int argc, char **argv) {
    eth_header *ethernet;
    arp_header *arp;
    int arg, c, set_router = 0, set_target = 0;
    int unidir = 0;
    char *interface = NULL;
    char *exitValue;
    FILE *config;
    char *router = NULL, *victim = NULL;

    if (argc < 2) {
        fprintf(stderr, "Too Few Arguments\n");
        fprintf(stderr, "Option -%c requires an argument.\n", optopt);
        fprintf(stderr, "[USAGE] => %s -i \"[wlan0 or etho0]\" \n-r \"{ROUTER_IP:ROUTER_MAC}\" \n-t \"{VICTIM_IP:VICTIM_MAC}\" \n", argv[0]);
        return 1;
    } else {
        while ((c = getopt(argc, argv, "i:ur:t:")) != -1) {
            switch (c) {
                case 'i':
                    interface = optarg;
                    break;
                case 'u':
                    // flag for uni-directional
                    unidir = 1;
                    break;
                case 'r':
                    // flag for router info
                    router = optarg;
                    set_router = 1;
                    break;
                case 't':
                    // flag for target info
                    victim = optarg;
                    set_target = 1;
                    break;
                case '?':
                    if (optopt == 'i') {
                        fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                        fprintf(stderr, "[USAGE] => %s -i \"[wlan0 or etho0]\" \n", argv[0]);
                    } else if (optopt == 'r') {
                        fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                        fprintf(stderr, "[USAGE] => %s -r {router_ip-router_mac} \n", argv[0]);
                    } else if (optopt == 't') {
                        fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                        fprintf(stderr, "[USAGE] => %s -t {target_ip-target_mac} \n", argv[0]);
                    } else if (isprint(optopt)) {
                        fprintf(stderr, "Unknown option '-%c'.\n", optopt);
                    } else {
                        fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
                    }
                    return 1;
            }
        }
    }

    MY_IP_ADDRS = allocate_strmem(INET_ADDRSTRLEN);
    MY_MAC_ADDRS = allocate_strmem(MAC_ADDR_STRLEN);

    ROUTER_IP_ADDRS = allocate_strmem(INET_ADDRSTRLEN);
    ROUTER_MAC_ADDRS = allocate_strmem(MAC_ADDR_STRLEN);

    VICTIM_IP_ADDRS = allocate_strmem(INET_ADDRSTRLEN);
    VICTIM_MAC_ADDRS = allocate_strmem(MAC_ADDR_STRLEN);

    // Create a Raw Socket
    RAW = create_raw_socket(ETH_P_ALL);

    MY_MAC_ADDRS = get_mac_addr(RAW, interface);
    MY_IP_ADDRS = get_ip_addr(RAW, interface);

    submit_log("MY IP ADDR: %s", MY_IP_ADDRS);
    submit_log("MY MAC ADDR: %s", MY_MAC_ADDRS);

    if (set_router == 1) {
        ROUTER_IP_ADDRS = strtok(router, "-");
        ROUTER_MAC_ADDRS = strtok(NULL, "-");

        submit_log("R IP ADDR: %s", ROUTER_IP_ADDRS);
        submit_log("R MAC ADDR: %s", ROUTER_MAC_ADDRS);
    }

    if (set_target == 1) {
        VICTIM_IP_ADDRS = strtok(victim, "-");
        VICTIM_MAC_ADDRS = strtok(NULL, "-");

        submit_log("V IP ADDR: %s", VICTIM_IP_ADDRS);
        submit_log("V MAC ADDR: %s", VICTIM_MAC_ADDRS);
    }



    arg = 1;
    if (setsockopt(RAW, SOL_SOCKET, SO_REUSEADDR, &arg, sizeof (arg)) == -1) {
        submit_log("[%s]\n", "setsockopt(): failed");
        exit(EXIT_FAILURE);
    }
    //BindRawSocketToInterface(argv[1], RAW,ETH_P_ALL); // Bind raw Socket to Interface

    if (unidir != 1) {
        // Enable IP Forwarding to capture 2 way traffic (Victim >> Router && Router >> Victim)
        if ((system("echo 1 > /proc/sys/net/ipv4/ip_forward")) == -1) {
            submit_log("%s", "unable to set ip_forward flag to 1");
            return EXIT_FAILURE;
        }
    } else {
        submit_log("%s", "IP Forwarding set to 0");
        // Allow to capture 1 way traffic (Victim >> Router) and do not pass the request to Router
        if ((system("echo 0 > /proc/sys/net/ipv4/ip_forward")) == -1) {
            submit_log("%s", "unable to set ip_forward flag to 0");
            return EXIT_FAILURE;
        }
    }

    // Clear the Firewall rules for the device
    if ((system("iptables -F")) == -1) {
        submit_log("%s", "Unable to Flush the Firewall rules");
        return EXIT_FAILURE;
    }


    while (TRUE) {
        ethernet = create_eth_header(MY_MAC_ADDRS, VICTIM_MAC_ADDRS, ETHERTYPE_ARP);
        arp = create_arp_header(MY_MAC_ADDRS, ROUTER_IP_ADDRS, VICTIM_MAC_ADDRS, VICTIM_IP_ADDRS, ARP_REPLY);
        send_packet(ethernet, arp, interface);

        ethernet = create_eth_header(MY_MAC_ADDRS, ROUTER_MAC_ADDRS, ETHERTYPE_ARP);
        arp = create_arp_header(MY_MAC_ADDRS, VICTIM_IP_ADDRS, ROUTER_MAC_ADDRS, ROUTER_IP_ADDRS, ARP_REPLY);
        send_packet(ethernet, arp, interface);

        sleep(1);

        config = fopen(CONFIG_FILE_LOC, "r");
        exitValue = malloc(sizeof (char *));
        rewind(config); // Seek to the beginning of the file
        if (fgets(exitValue, 100, config) != NULL) {
            fprintf(stdout, "%c\n", exitValue[0]);
            fflush(stdout);

            if (exitValue[0] == '1') {
                fprintf(stdout, "Exiting.....\n");
                break;
            }
        }

        free(exitValue);
        fclose(config);

    }

    return 0;
}
コード例 #25
0
ファイル: dwmstatus.c プロジェクト: KaiSforza/dwmstatus
/*
 * setup the status bar here
 */
int
status(int tostatusbar)
{
    char *status = NULL;
    char *avgs = NULL;
    char *time = NULL;
    char *batt = NULL;
    char *net = NULL;
    char *net_sec = NULL;
    char *temp = NULL;
    char *ipaddr = NULL;
    char *ipaddr_sec = NULL;

#ifdef NET_DEVICE_PRIMARY
    char *net_device_up = NET_DEVICE_PRIMARY;
#endif
#ifdef NET_DEVICE_SECONDARY
    char *net_device_sec = NET_DEVICE_SECONDARY;
#endif

    time_t count60 = 0;
    time_t count10 = 0;

    if (!(dpy = XOpenDisplay(NULL)) && tostatusbar == 0) {
        fprintf(stderr, "dwmstatus: cannot open display.\n");
        return 1;
    }

    for (;;sleep(0)) {
        /* Update every minute */
        if (runevery(&count60, 60)) {
            free(time);

            time  = mktimes("%Y/%m/%d %H:%M", TIMEZONE);
        }
        /* Update every 10 seconds */
        if (runevery(&count10, 10)) {
#ifdef BATT_PATH
            free(batt);
            batt = getbattery(BATT_PATH);
#endif
#ifdef TEMP_SENSOR_PATH
#ifdef TEMP_SENSOR_UNIT
            free(avgs);
            free(temp);

            avgs   = loadavg();
            temp   = gettemperature(TEMP_SENSOR_PATH, TEMP_SENSOR_UNIT);
            SFREE(temp);
#endif
#endif
        }
        /* Update every second */
#ifdef NET_DEVICE_PRIMARY
        net    = get_netusage(net_device_up);
        ipaddr = get_ip_addr(net_device_up);
#endif
#ifdef NET_DEVICE_SECONDARY
        net_sec = get_netusage(net_device_sec);
        ipaddr_sec = get_ip_addr(net_device_sec);
#endif

        /* Format of display */
        status = smprintf("%s%s%s%s%s%s",
            ipaddr      == NULL ? "" : smprintf(" %s (%s) |", net, ipaddr),
            ipaddr_sec  == NULL ? "" : smprintf(" %s (%s) |", net_sec, ipaddr_sec),
            batt        == NULL ? "" : smprintf(" %s", batt),
            avgs        == NULL ? "" : smprintf(" [%s]", avgs),
            time        == NULL ? "" : smprintf(" %s", temp),
            time        == NULL ? "" : smprintf(" | %s", time)
            );
        SFREE(ipaddr)
        free(net);
        SFREE(ipaddr_sec)
        free(net_sec);

        if(tostatusbar == 0)
            setstatus(status);
        else
            puts(status);

        free(status);
    }
    return 0;
}
コード例 #26
0
ファイル: udp_fw_update.c プロジェクト: hadmack/UHD-Mirror
//Firmware update packet handler
void handle_udp_fw_update_packet(struct socket_address src, struct socket_address dst,
                                 unsigned char *payload, int payload_len) {

  const usrp2_fw_update_data_t *update_data_in = (usrp2_fw_update_data_t *) payload;

  usrp2_fw_update_data_t update_data_out;
  usrp2_fw_update_id_t update_data_in_id = update_data_in->id;

  //ensure that the protocol versions match
/*  if (payload_len >= sizeof(uint32_t) && update_data_in->proto_ver != USRP2_FW_COMPAT_NUM){
    printf("!Error in update packet handler: Expected compatibility number %d, but got %d\n",
        USRP2_FW_COMPAT_NUM, update_data_in->proto_ver
      );
      update_data_in_id = USRP2_FW_UPDATE_ID_OHAI_LOL; //so we can respond
  }
*/
  //ensure that this is not a short packet
  if (payload_len < sizeof(usrp2_fw_update_data_t)){
      printf("!Error in update packet handler: Expected payload length %d, but got %d\n",
          (int)sizeof(usrp2_fw_update_data_t), payload_len
      );
      update_data_in_id = USRP2_FW_UPDATE_ID_WAT;
  }

  switch(update_data_in_id) {
  case USRP2_FW_UPDATE_ID_OHAI_LOL: //why hello there you handsome devil
    update_data_out.id = USRP2_FW_UPDATE_ID_OHAI_OMG;
    memcpy(&update_data_out.data.ip_addr, (void *)get_ip_addr(), sizeof(struct ip_addr));
    //this is to stop streaming for the folks who think updating while streaming is a good idea
    sr_rx_ctrl0->cmd = 1 << 31 | 1 << 28; //no samples now
    sr_rx_ctrl0->time_secs = 0;
    sr_rx_ctrl0->time_ticks = 0; //latch the command
    sr_rx_ctrl1->cmd = 1 << 31 | 1 << 28; //no samples now
    sr_rx_ctrl1->time_secs = 0;
    sr_rx_ctrl1->time_ticks = 0; //latch the command
    sr_tx_ctrl->cyc_per_up = 0;
    break;

  case USRP2_FW_UPDATE_ID_WATS_TEH_FLASH_INFO_LOL: //query sector size, memory size so the host can mind the boundaries
    update_data_out.data.flash_info_args.sector_size_bytes = spi_flash_sector_size();
    update_data_out.data.flash_info_args.memory_size_bytes = spi_flash_memory_size();
    update_data_out.id = USRP2_FW_UPDATE_ID_HERES_TEH_FLASH_INFO_OMG;
    break;

  case USRP2_FW_UPDATE_ID_I_CAN_HAS_HW_REV_LOL: //get the hardware revision of the platform for validation checking
    update_data_out.data.hw_rev = (uint32_t) get_hw_rev();
    update_data_out.id = USRP2_FW_UPDATE_ID_HERES_TEH_HW_REV_OMG;
    break;

  case USRP2_FW_UPDATE_ID_ERASE_TEH_FLASHES_LOL: //out with the old
    spi_flash_async_erase_start(&spi_flash_async_state, update_data_in->data.flash_args.flash_addr, update_data_in->data.flash_args.length);
    update_data_out.id = USRP2_FW_UPDATE_ID_ERASING_TEH_FLASHES_OMG;
    break;

  case USRP2_FW_UPDATE_ID_R_U_DONE_ERASING_LOL:
    //poll for done, set something in the reply packet
    //spi_flash_async_erase_poll() also advances the state machine, so you should call it reasonably often to get things done quicker
    if(spi_flash_async_erase_poll(&spi_flash_async_state)) update_data_out.id = USRP2_FW_UPDATE_ID_IM_DONE_ERASING_OMG;
    else update_data_out.id = USRP2_FW_UPDATE_ID_NOPE_NOT_DONE_ERASING_OMG;
    break;

  case USRP2_FW_UPDATE_ID_WRITE_TEH_FLASHES_LOL: //and in with the new
    //spi_flash_program() goes pretty quick compared to page erases, so we don't bother polling -- it'll come back in some milliseconds
    //if it doesn't come back fast enough, we'll just write smaller packets at a time until it does
    spi_flash_program(update_data_in->data.flash_args.flash_addr, update_data_in->data.flash_args.length, update_data_in->data.flash_args.data);
    update_data_out.id = USRP2_FW_UPDATE_ID_WROTE_TEH_FLASHES_OMG;
    break;

  case USRP2_FW_UPDATE_ID_READ_TEH_FLASHES_LOL: //for verify
    spi_flash_read(update_data_in->data.flash_args.flash_addr,  update_data_in->data.flash_args.length, update_data_out.data.flash_args.data);
    update_data_out.id = USRP2_FW_UPDATE_ID_KK_READ_TEH_FLASHES_OMG;
    break;

  case USRP2_FW_UPDATE_ID_RESET_MAH_COMPUTORZ_LOL: //for if we ever get the ICAP working
    //should reset via icap_reload_fpga(uint32_t flash_address);
    update_data_out.id = USRP2_FW_UPDATE_ID_RESETTIN_TEH_COMPUTORZ_OMG;
    //you should note that if you get a reply packet to this the reset has obviously failed
    icap_reload_fpga(0);
    break;

//  case USRP2_FW_UPDATE_ID_KTHXBAI: //see ya
//    break;

  default: //uhhhh
    update_data_out.id = USRP2_FW_UPDATE_ID_WAT;
  }
  send_udp_pkt(USRP2_UDP_UPDATE_PORT, src, &update_data_out, sizeof(update_data_out));
}
コード例 #27
0
int WirelessNetworkInit()
{
	int ret = -1;
	int nDhcpFlag = -1;
	SYS_INFO sysInfo;
	WIFI_PARAM wifiParam;
	NET_PARAM netParam;
	char ip[16];
	char mac_addr[32] = {0};
	char command_buffer[256]= {0};
	char buffer_cache[128]= {0};
	
	ret = getWifiParam(&wifiParam);
	if (ret < 0)
	{
		return -1;
	}
			
	ret = getNetParam(&netParam);
	if (ret < 0)
	{
		return -1;
	}

	system("ifconfig ra0 192.168.5.5 up");
	memset(mac_addr, 0, 32);
	if (get_net_phyaddr_ext(ETH_WIRELESS_DEV, mac_addr) == 0)
	{
		memcpy(wifiParam.strPhyAddr, mac_addr, 6);
	}
	ret = setWifiParam(&wifiParam);
	if (ret < 0)
	{
		return -1;
	}
	
	if (wifiParam.nOnFlag == 1) 	// 启用无线
	{
		//增加wifi 状态指示
		if(wifi_setup(wifiParam) == 0)
		{
			wifiParam.Reserve = 1;
			ret = setWifiParam(&wifiParam);
			if (ret < 0)
			{
				return -1;
			}
		}
		
#if 1		
		// DHCP设置
		if (wifiParam.nDhcpOnFlag == 1)
		{
			getSysInfoParam(&sysInfo);
			nDhcpFlag = dhcp_setup(ETH_WIRELESS_DEV, sysInfo.strDeviceName);
		}
		else
		{
			nDhcpFlag = -1;
		}
		
		// 固定IP设置
		memset(ip, 0, 16);
		get_ip_addr(ETH_WIRELESS_DEV, ip);
		
		printf("dhcp_setup(WIRELESS): %d %s\n", nDhcpFlag, ip);

		if (nDhcpFlag != 0 || strlen(ip)<=0 || wifiParam.nDhcpOnFlag==0)
		{
			// Add the code by lvjh, 2008-03-22
			unsigned int add1 = 0;
			unsigned int add2 = 0;
			unsigned int add3 = 0;
			unsigned int add4 = 0;
	
			unsigned int add5 = 0;
			unsigned int add6 = 0;
			unsigned int add7 = 0;
			unsigned int add8 = 0;
				
			//判断是不是用户输入的wifi
			sleep(10);
			printf("wifiParam.pReserve[0]  = %d\n", wifiParam.pReserve[0]);
			if(wifiParam.pReserve[0] == 1){
				strcpy(wifiParam.byServerIp, netParam.byServerIp);
				strcpy(wifiParam.byDnsAddr, netParam.byDnsAddr);
				strcpy(wifiParam.byGateway, netParam.byGateway);
				strcpy(wifiParam.byServerMask, netParam.byServerMask);
				
				ret = setWifiParam(&wifiParam);
				if (ret < 0)
				{
					return -1;
				}
			}
			
			printf("DVS IP(WIRELESS): %s\n", wifiParam.byServerIp);
			

			#if 0
			if (set_ip_addr(ETH_WIRELESS_DEV, wifiParam.byServerIp) < 0)
			{
				printf("set_ip_addr(%s) Failed!\n", wifiParam.byServerIp);
	
				set_ip_addr(ETH_WIRELESS_DEV, DEFAULT_WIRELESS_IP);
				set_mask_addr(ETH_WIRELESS_DEV, DEFAULT_WIRELESS_MASK);
				//set_gateway_addr(DEFAULT_WIRELESS_GATEWAY);
				set_gateway_addr_ext(ETH_WIRELESS_DEV, DEFAULT_WIRELESS_GATEWAY);
				//return -1;
			}
			#endif
			
			sprintf(buffer_cache, "%s %s %s", "ifconfig",  ETH_WIRELESS_DEV, wifiParam.byServerIp);
			system(buffer_cache);
			
		
			if (set_mask_addr(ETH_WIRELESS_DEV, wifiParam.byServerMask) < 0)
			{
				printf("set_mask_addr(%s) Failed!\n", wifiParam.byServerMask);
		
				set_mask_addr(ETH_WIRELESS_DEV, DEFAULT_WIRELESS_MASK);
				//set_gateway_addr(DEFAULT_WIRELESS_GATEWAY);
				set_gateway_addr_ext(ETH_WIRELESS_DEV, DEFAULT_WIRELESS_GATEWAY);
				//return -1;
			}
	
			//printf("Old GateWay: %s\n", wifiParam.byGateway);
			//sscanf(wifiParam.byServerIp, "%d.%d.%d.%d", &add1, &add2, &add3, &add4);
			//sscanf(wifiParam.byGateway, "%d.%d.%d.%d", &add5, &add6, &add7, &add8);
			//sprintf(wifiParam.byGateway, "%d.%d.%d.%d", add1, add2, add3, add8);
			//printf("New GateWay: %s\n", wifiParam.byGateway);
				
			//if (set_gateway_addr(wifiParam.byGateway) < 0)
			if (set_gateway_addr_ext(ETH_WIRELESS_DEV, wifiParam.byGateway) < 0)
			{
				printf("set_gateway_addr(%s) Failed!\n", wifiParam.byGateway);
				//set_gateway_addr(DEFAULT_WIRELESS_GATEWAY);
				set_gateway_addr_ext(ETH_WIRELESS_DEV, DEFAULT_WIRELESS_GATEWAY);
				//return -1;
			}
		}

		// DNS设置
		if (wifiParam.nDhcpOnFlag == 1)
		{
			char localIP[16];
			char gateway[16];
			
			memset(localIP, 0, 16);
			memset(gateway, 0, 16);
	
			//ret = get_gateway_addr(gateway);
			ret = get_gateway_addr_ext(ETH_WIRELESS_DEV, gateway);
			if (ret == 0)
			{
				printf("GateWay(WIRELESS): %s\n", gateway);

				set_dns_addr(gateway);
				//add_dns_addr(gateway);
				
				strcpy(wifiParam.byGateway, gateway);
				strcpy(wifiParam.byDnsAddr, gateway);
			}
			ret = get_ip_addr(ETH_WIRELESS_DEV, localIP);
			if (ret == 0)
			{
				printf("DHCP: get_ip_addr: %s\n", localIP);
				strcpy(wifiParam.byServerIp, localIP);
			}
			printf("DHCP: %s %s\n", ETH_WIRELESS_DEV, localIP);
			
		
			wifiParam.Reserve = 1;
			setWifiParam(&wifiParam);
		}
		else
		{
			wifiParam.Reserve = 1;
			set_dns_addr(wifiParam.byGateway);
			
			
			//add_dns_addr(wifiParam.byGateway);
		}
#endif	
	}
	else
	{
		wifiParam.Reserve = 1;
		setWifiParam(&wifiParam);
	}
	return 0;
}
コード例 #28
0
ファイル: voglperfrun.cpp プロジェクト: TrepidJon/voglperf
//----------------------------------------------------------------------------------------------------------------------
// main
//----------------------------------------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
    voglperf_data_t data(get_ip_addr(), "8081");

    parse_appid_file(data.installed_games);

    /*
     * Parse command line.
     */
    std::vector<struct argp_option> argp_options;

    // Add argp options.
    for (size_t i = 0; i < sizeof(g_options) / sizeof(g_options[0]); i++)
    {
        struct argp_option opt;

        memset(&opt, 0, sizeof(opt));
        opt.name = g_options[i].name;
        opt.key = g_options[i].key;
        opt.doc = g_options[i].desc;
        opt.group = 1;

        argp_options.push_back(opt);
    }

    static const struct argp_option s_options[] =
    {
        { "ipaddr"         , 'i' , "IPADDR" , 0 , "Web IP address."                                                         , 2 },
        { "port"           , 'p' , "PORT"   , 0 , "Web port."                                                               , 2 },

        { "show-type-list" , -2  , 0        , 0 , "Produce list of whitespace-separated words used for command completion." , 3 },
        { "help"           , '?' , 0        , 0 , "Print this help message."                                                , 3 },

        { 0, 0, 0, 0, NULL, 0 }
    };
    argp_options.insert(argp_options.end(), s_options, s_options + sizeof(s_options) / sizeof(s_options[0]));

    struct argp argp = { &argp_options[0], parse_options, 0, "Vogl perf launcher.", NULL, NULL, NULL };
    argp_parse(&argp, argc, argv, ARGP_NO_HELP, 0, &data);

    /*
     * Initialize our message queue used to communicate with our hook.
     */
    data.msqid = msgget(IPC_PRIVATE, IPC_CREAT | S_IRUSR | S_IWUSR);
    if (data.msqid == -1)
    {
        errorf("ERROR: msgget() failed: %s\n", strerror(errno));
    }

    /*
     * Start our web server...
     */
    webby_init_t init;

    init.bind_address = data.ipaddr.c_str();
    init.port = (unsigned short)atoi(data.port.c_str());
    init.user_data = &data;
    init.verbose = !!(data.flags & F_VERBOSE);
    init.ws_connected_pfn = webby_connected_callback;
    init.uri_dispatch_pfn = webby_uri_dispatch_callback;

    webby_start(init);

    pthread_mutex_init(&data.lock, NULL);

    pthread_t threadid = (pthread_t)-1;
    if (pthread_create(&threadid, NULL, &editline_threadproc, (void *)&data) != 0)
        printf("WARNING: pthread_create failed: %s\n", strerror(errno));

    /*
     * Main loop.
     */

    // If we were specified a game to start on the command line, then start it
    //  and exit after it finishes.
    bool quit_on_game_exit = !!data.gameid.size();
    if (quit_on_game_exit)
    {
        data.commands.push_back("status");
        data.commands.push_back("game start");
    }

    while (!(data.flags & F_QUIT))
    {
        struct timeval timeout;

        // Handle commands from stdin.
        if (data.thread_commands.size())
        {
            pthread_mutex_lock(&data.lock);
            data.commands.insert(data.commands.end(), data.thread_commands.begin(), data.thread_commands.end());
            data.thread_commands.clear();
            pthread_mutex_unlock(&data.lock);
        }

        // Have Webby wait .5s unless there are commands to execute.
        timeout.tv_sec = 0;
        timeout.tv_usec = data.commands.size() ? 5 : 500 * 1000;

        // Update web page.
        webby_update(&data.commands, &timeout);

        // Handle any commands.
        process_commands(data);

        // Grab output if game is running.
        update_app_output(data);

        // Grab messages from running game.
        update_app_messages(data);

        if (quit_on_game_exit && (data.run_data.pid == (uint64_t)-1))
            data.commands.push_back("quit");
    }

    /*
     * Shutdown.
     */
    webby_ws_printf("\nDone.\n");

    if (threadid != (pthread_t)-1)
    {
        void *status = NULL;
        pthread_cancel(threadid);
        pthread_join(threadid, &status);
    }

    // Update and terminate web server.
    webby_update(&data.commands, NULL);
    webby_end();

    pthread_mutex_destroy(&data.lock);

    // Destroy our message queue.
    msgctl(data.msqid, IPC_RMID, NULL);
    data.msqid = -1;
    return 0;
}
コード例 #29
0
ファイル: kv_root_server.cpp プロジェクト: keoyeop/tfs
    /** handle single packet */
    tbnet::IPacketHandler::HPRetCode KvRootServer::handlePacket(tbnet::Connection *connection, tbnet::Packet *packet)
    {
      tbnet::IPacketHandler::HPRetCode hret = tbnet::IPacketHandler::FREE_CHANNEL;
      bool bret = NULL != connection && NULL != packet;
      if (bret)
      {
        TBSYS_LOG(DEBUG, "receive pcode : %d", packet->getPCode());
        if (!packet->isRegularPacket())
        {
          bret = false;
          TBSYS_LOG(WARN, "control packet, pcode: %d", dynamic_cast<tbnet::ControlPacket*>(packet)->getCommand());
        }
        if (bret)
        {
          BasePacket* bpacket = dynamic_cast<BasePacket*>(packet);
          bpacket->set_connection(connection);
          bpacket->setExpireTime(MAX_RESPONSE_TIME);
          bpacket->set_direction(static_cast<DirectionStatus>(bpacket->get_direction()|DIRECTION_RECEIVE));

          if (bpacket->is_enable_dump())
          {
            bpacket->dump();
          }
          int32_t pcode = bpacket->getPCode();
          int32_t iret = common::TFS_SUCCESS;

          if (common::TFS_SUCCESS == iret)
          {
            hret = tbnet::IPacketHandler::KEEP_CHANNEL;
            switch (pcode)
            {
            case REQ_KV_RT_MS_KEEPALIVE_MESSAGE:
              ms_rs_heartbeat_workers_.push(bpacket, 0/* no limit */, false/* no block */);
              break;
            default:
              if (!main_workers_.push(bpacket, work_queue_size_))
              {
                bpacket->reply_error_packet(TBSYS_LOG_LEVEL(ERROR),STATUS_MESSAGE_ERROR, "%s, task message beyond max queue size, discard", get_ip_addr());
                bpacket->free();
              }
              break;
            }
          }
          else
          {
            bpacket->free();
            TBSYS_LOG(WARN, "the msg: %d will be ignored", pcode);
          }
        }
      }
      return hret;
    }
コード例 #30
0
ファイル: main.c プロジェクト: herzfeldd/parallel_wrapper
int main(int argc, char **argv)
{
	int RC;
	pthread_attr_t attr;
	default_pthead_attr(&attr);
	pthread_mutex_init(&keep_alive_mutex, NULL);
	/* Lock the keep-alive mutex */
	pthread_mutex_lock(&keep_alive_mutex);

	/* Allocate a new parallel_wrapper structure */
	parallel_wrapper *par_wrapper = (parallel_wrapper *)calloc(1, sizeof(struct parallel_wrapper));
	if (par_wrapper == (parallel_wrapper *)NULL)
	{
		print(PRNT_ERR, "Unable to allocate space for parallel wrapper\n");
		return 1;
	}
	/* Install command signal handlers */
	signal(SIGINT, handle_exit_signal);
	signal(SIGTERM, handle_exit_signal);
	signal(SIGHUP, handle_exit_signal);

	/* Create structures for this machine */
	par_wrapper -> this_machine = calloc(1, sizeof(struct machine));
	if (par_wrapper -> this_machine == (machine *)NULL)
	{
		print(PRNT_ERR, "Unable to allocate space for this machine\n");
		return 1;
	}

	/* Fill in the default values for port ranges */
	par_wrapper -> low_port = LOW_PORT;
	par_wrapper -> high_port = HIGH_PORT;
	/* Fill in other default values */
	par_wrapper -> this_machine -> rank = -1;
	par_wrapper -> num_procs = -1; 
	par_wrapper -> command_socket = -1;
	par_wrapper -> pgid = -1;
	par_wrapper -> ka_interval = KA_INTERVAL;
	par_wrapper -> timeout = TIMEOUT;
	/* Default mutex state */
	pthread_mutex_init(&par_wrapper -> mutex, NULL);
	/* Allocate a list of symlinks */
	par_wrapper -> symlinks = sll_get_list();
	/* Get the initial working directory */
	par_wrapper -> this_machine -> iwd = getcwd(NULL, 0); /* Allocates space */
	/* Determine our name */
	uid_t uid = getuid();
	struct passwd *user_stats = getpwuid(uid);
	if (user_stats == (struct passwd *)NULL)
	{
		print(PRNT_WARN, "Unable to determine the name of the current user - assuming 'nobody'\n");
		par_wrapper -> this_machine -> user = strdup("nobody");
	}
	else
	{
		par_wrapper -> this_machine -> user = strdup(user_stats -> pw_name);	

	}

	/* Parse environment variables and command line arguments */
	parse_environment_vars(par_wrapper);
	parse_args(argc, argv, par_wrapper);

	/* Set the environment variables */
	set_environment_vars(par_wrapper);

	/* Check that required values are filled in */
	if (par_wrapper -> this_machine -> rank < 0)
	{
		print(PRNT_ERR, "Invalid rank (%d). Environment variable or command option not set.\n", 
			par_wrapper -> this_machine -> rank);
		return 2;
	}
	if (par_wrapper -> num_procs < 0)
	{
		print(PRNT_ERR, "Invalid number of processors (%d). Environment variable or command option not set.\n",
			par_wrapper -> num_procs);
		return 2;
	}
	if (par_wrapper -> timeout <= (2*par_wrapper -> ka_interval))
	{
		print(PRNT_WARN, "Keep-alive interval and timeout too close. Using default values.\n");
		par_wrapper -> timeout = TIMEOUT;
		par_wrapper -> ka_interval = KA_INTERVAL;
	}

	/* Get the IP address for this machine */
	par_wrapper -> this_machine -> ip_addr = get_ip_addr();
	debug(PRNT_INFO, "IP Addr: %s\n", par_wrapper -> this_machine -> ip_addr);
	if (par_wrapper -> this_machine -> ip_addr == (char *)NULL)
	{
		print(PRNT_ERR, "Unable to get the IP address for this machine\n");
		return 2;
	}
	
	/* Get a command port for this machine */
	RC = get_bound_dgram_socket_by_range(par_wrapper -> low_port, 
		par_wrapper -> high_port, &par_wrapper -> this_machine -> port, 
		&par_wrapper -> command_socket);		
	if (RC != 0)
	{
		print(PRNT_ERR, "Unable to bind to command socket\n");
		return 2;
	}
	else
	{
		debug(PRNT_INFO, "Bound to command port: %d\n", par_wrapper -> this_machine -> port);
	}

	/** 
	 * If this is rank 0, point rank 0 to this_machine, otherwise allocate
	 * a new structure for the master
	 */
	if (par_wrapper -> this_machine -> rank == MASTER)
	{
		par_wrapper -> master = par_wrapper -> this_machine;
		par_wrapper -> machines = (machine **) calloc(par_wrapper -> num_procs, sizeof(machine *));
		if (par_wrapper -> machines == (machine **)NULL)
		{
			print(PRNT_ERR, "Unable to allocate space for machines array\n");
			return 3;
		}
		par_wrapper -> machines[0] = par_wrapper -> master;
	}
	else
	{
		par_wrapper -> master = (machine *)calloc(1, sizeof(struct machine));
		if (par_wrapper -> master == (machine *)NULL)
		{
			print(PRNT_ERR, "Unable to allocate space for master\n");
			return 2;
		}
		par_wrapper -> master -> rank = MASTER;
	}
	
	/* Create the scratch directory */
	create_scratch(par_wrapper);

	/* Gather the necessary chirp information */
	RC = chirp_info(par_wrapper);
	if (RC != 0)
	{
		print(PRNT_ERR, "Failure sending/recieving chirp information\n");
		return 2;
	}

	/* Create the listener */
	pthread_create(&par_wrapper -> listener, &attr, &udp_server, (void *)par_wrapper);

	/* If I am the MASTER, wait for all ranks to register */
	if (par_wrapper -> this_machine -> rank == MASTER)
	{
		int i, j;
		j = 0; /* Timeout = 0 */
		while ( 1 )
		{
			int finished = 1;
			for (i = 0; i < par_wrapper -> num_procs; i++)
			{
				if (par_wrapper -> machines[i] == NULL)
				{
					finished = 0;
				}
				
				if ((j % par_wrapper -> ka_interval) == 0 && par_wrapper -> machines[i] == NULL)
				{
					debug(PRNT_INFO, "Waiting for registration from rank %d\n", i);
				}
			}
			j++; /* Waiting for timeout */
			if (j >= par_wrapper -> timeout)
			{
				finished = 1;
				for (i = 0; i < par_wrapper -> num_procs; i++)
				{
					if (par_wrapper -> machines[i] == NULL)
					{
						print(PRNT_WARN, "Rank %d not registered - giving up on it\n", i);
					}
				}
			}	
			if (finished == 1)
			{
				break;
			}
			sleep(1);
		}
		debug(PRNT_INFO, "Finished machine registration.\n", par_wrapper -> num_procs);
		/* Create the machines file */
		RC = create_machine_file(par_wrapper);
		if (RC != 0)
		{
			print(PRNT_ERR, "Unable to create the machines files");
			cleanup(par_wrapper, 5);
		}
		RC = create_ssh_config(par_wrapper);
		if (RC != 0)
		{
			print(PRNT_ERR, "Unable to create the machines files");
			cleanup(par_wrapper, 5);
		}
	}
	else /* Register with the master */
	{
		struct timeval old_time = par_wrapper -> master -> last_alive;
		while ( 1 )
		{
			RC = register_cmd(par_wrapper -> command_socket, par_wrapper -> this_machine -> rank,
				par_wrapper -> this_machine -> cpus,
				par_wrapper -> this_machine -> iwd, par_wrapper -> this_machine -> user, par_wrapper -> master -> ip_addr, 
				par_wrapper -> master -> port);		
			sleep(1);
			if (RC == 0 && 
			   ((old_time.tv_sec != par_wrapper -> master -> last_alive.tv_sec) || 
			   (old_time.tv_usec != par_wrapper -> master -> last_alive.tv_usec)))
			{
				break;
			}
			debug(PRNT_INFO, "Waiting for ACK from mater\n"); 
			/* Retrieve chirp information (in case it changed since the last time) */
			chirp_info(par_wrapper);
		}
	}

	/* MASTER - Identify unique hosts */
	if (par_wrapper -> this_machine -> rank == MASTER)
	{
		int i, j;
		for (i = 0; i < par_wrapper -> num_procs; i++)
		{
			if (par_wrapper -> machines[i] == (machine *)NULL)
			{
				continue;
			}
			/* All machines are initially unique */
			par_wrapper -> machines[i] -> unique = 1; 
		}
		for (i = 0; i < par_wrapper -> num_procs; i++)
		{
			if (par_wrapper -> machines[i] == (machine *)NULL)
			{
				continue;
			}
			if (par_wrapper -> machines[i] -> unique == 0)
			{
				continue; /* This host is already not unique */
			}
			for (j = i + 1; j < par_wrapper -> num_procs; j++)
			{
				if (par_wrapper -> machines[j] == (machine *)NULL)
				{
					continue;
				}
				if (par_wrapper -> machines[j] -> unique == 0)
				{
					continue; /* This host is already not unique */
				}	
				if (strcmp(par_wrapper -> machines[i] -> ip_addr, par_wrapper -> machines[j] -> ip_addr) == 0)
				{
					par_wrapper -> machines[j] -> unique = 0;
					debug(PRNT_INFO, "Rank %d (%s:%d) is not unique (some host as %d).\n", 
							j, par_wrapper -> machines[j] -> ip_addr, 
							par_wrapper -> machines[j] -> port, i);
				}	
			}
		}
	}
	
	int shared_fs = 1; /* Flag which denotes a shared fs */

	/* If I am rank 0 - determine if we need to create a fake file system */
	if (par_wrapper -> this_machine -> rank == MASTER)
	{
		int i;
		for (i = 0; i < par_wrapper -> num_procs; i++)
		{
			if (par_wrapper -> machines[i] == (machine *)NULL)
			{
				continue;
			}
			if (strcmp(par_wrapper -> machines[i] -> iwd, par_wrapper -> master -> iwd) != 0)
			{
				shared_fs = 0;
			}
		}
		if (shared_fs == 0)
		{
			char fake_fs[1024];
			time_t curr_time = time(NULL);
			snprintf(fake_fs, 1024, "/tmp/condor_hydra_%d_%ld", par_wrapper -> cluster_id, 
					(long)curr_time);
			debug(PRNT_INFO, "Using fake file system (%s). IWD's across ranks differ\n", fake_fs);
			for (i = 0; i < par_wrapper -> num_procs; i++)
			{
				if (par_wrapper -> machines[i] == (machine *)NULL)
				{
					continue;
				}
				if (! par_wrapper -> machines[i] -> unique)
				{
					continue;
				}
				/* Send the command to create softlinks */
				struct timeval old_time = par_wrapper -> machines[i] -> last_alive;
				while ( 1 )
				{
					RC = create_link(par_wrapper -> command_socket, par_wrapper -> machines[i] -> iwd,
							fake_fs, par_wrapper -> machines[i] -> ip_addr, 
							par_wrapper -> machines[i] -> port);
					usleep(100000); /* Sleep for 1/10th of a second */
					if (RC == 0 && 
					   ((old_time.tv_sec != par_wrapper -> machines[i] -> last_alive.tv_sec) || 
					   (old_time.tv_usec != par_wrapper -> machines[i] -> last_alive.tv_usec)))
					{
						break;
					}
					debug(PRNT_INFO, "Waiting for ACK from rank %d\n", i);
				}
			}
			par_wrapper -> shared_fs = strdup(fake_fs);
		}
		else 
		{
			par_wrapper -> shared_fs = strdup(par_wrapper -> master -> iwd);
			debug(PRNT_INFO, "Using a shared file system, IWD = %s\n", par_wrapper -> master -> iwd);
		}
	}
	/* Unlock the keepalive mutex */
	pthread_mutex_unlock(&keep_alive_mutex);

	/* Start up the MPI executable */
	if (par_wrapper -> this_machine -> rank == MASTER)
	{
		par_wrapper -> child_pid = fork();
		if (par_wrapper -> child_pid == (pid_t) -1)
		{
			print(PRNT_ERR, "Fork failed\n");
			cleanup(par_wrapper, 10);
		}
		else if (par_wrapper -> child_pid == (pid_t) 0)
		{
			/* I am the child */
			prctl(PR_SET_PDEATHSIG, SIGTERM);
			/* Set environment variables */
			char *machine_file = join_paths(par_wrapper -> scratch_dir, MACHINE_FILE);
			char *ssh_config = join_paths(par_wrapper -> scratch_dir, SSH_CONFIG);
			setenv("MACHINE_FILE", machine_file, 1); 
			setenv("SSH_CONFIG", ssh_config, 1);
		   	free(machine_file);
			free(ssh_config);	
			char *ssh_wrapper = join_paths(par_wrapper -> scratch_dir, SSH_WRAPPER);
			setenv("SSH_WRAPPER", ssh_wrapper, 1);
			free(ssh_wrapper);
			char temp_str[1024];
			
			snprintf(temp_str, 1024, "%d", par_wrapper -> num_procs);
			setenv("NUM_MACHINES", temp_str, 1);
		
			/* Determine the total number of cpus allocated to this task */
			int total_cpus = 0;
			int i;
			for (i = 0; i < par_wrapper -> num_procs; i++)
			{
				if (par_wrapper -> machines[i] == (machine *)NULL)
				{
					continue;
				}
				total_cpus += par_wrapper -> machines[i] -> cpus;
			}
			snprintf(temp_str, 1024, "%d", total_cpus);
			setenv("CPUS", temp_str, 1);
			setenv("NUM_PROCS", temp_str, 1);

			snprintf(temp_str, 1024, "%d", par_wrapper -> this_machine -> rank);
			setenv("RANK", temp_str, 1);
			
			snprintf(temp_str, 1024, "%d", par_wrapper -> cluster_id);
			setenv("CLUSTER_ID", temp_str, 1);
			
			snprintf(temp_str, 1024, "%d", par_wrapper -> this_machine -> port);
			setenv("CMD_PORT", temp_str, 1);
			
			snprintf(temp_str, 1024, "%d", par_wrapper -> this_machine -> cpus);
			setenv("REQUEST_CPUS", temp_str, 1);

			setenv("SCRATCH_DIR", par_wrapper -> scratch_dir, 1);
			setenv("IWD", par_wrapper -> this_machine -> iwd, 1);
			setenv("IP_ADDR", par_wrapper -> this_machine -> ip_addr, 1);
			setenv("TRANSFER_FILES", shared_fs != 0 ? "TRUE" : "FALSE", 1); 
			setenv("SHARED_FS", shared_fs != 0 ? par_wrapper -> this_machine -> iwd : par_wrapper -> shared_fs, 1);
			setenv("SHARED_DIR", shared_fs != 0 ? par_wrapper -> this_machine -> iwd : par_wrapper -> shared_fs, 1);
			setenv("SCHEDD_IWD", par_wrapper -> this_machine -> schedd_iwd, 1);
			/* TODO: SSH ENVS */

			/* Search in path */
			int process_RC = execvp(par_wrapper -> executable[0], &par_wrapper -> executable[0]);
			if (process_RC != 0)
			{
				print(PRNT_ERR, "%s\n", get_exec_error_msg(errno, par_wrapper -> executable[0]));
			}
			exit(process_RC);	
		}
		else
		{
			/* I am the parent */
			int child_status = 0;
			/* Create a new group for the child processes */
			par_wrapper -> pgid = setpgid(par_wrapper -> child_pid, 
					par_wrapper -> child_pid);			
			if (par_wrapper -> pgid < 0)
			{
				print(PRNT_WARN, "Unable to set process group for children\n");
			}
			
			waitpid(par_wrapper -> child_pid, &child_status, WUNTRACED); /* Wait for the child to finish */
			cleanup(par_wrapper, child_status);
		}
	}

	/* Always wait for the listener */
	pthread_join(par_wrapper -> listener, NULL);

	return 0;
}