void net_init(const uint8_t *mac_address, struct ip_info *p_ip_info, const uint8_t *hostname, bool use_dhcp) { uint16_t i; net_timers_init(); if (use_dhcp) { p_ip_info->ip.addr = 0; p_ip_info->gw.addr = 0; p_ip_info->netmask.addr = 0; } else { arp_init(mac_address, p_ip_info); } ip_init(mac_address, p_ip_info); if (use_dhcp) { if (dhcp_client(mac_address, p_ip_info, hostname) < 0) { DEBUG_PUTS("DHCP Client failed"); } else { arp_init(mac_address, p_ip_info); ip_set_ip(p_ip_info); } } for (i = 0; i < ETH_ADDR_LEN; i++) { s_mac_address[i] = mac_address[i]; } uint8_t *src = (uint8_t *) p_ip_info; uint8_t *dst = (uint8_t *) &s_ip_info; for (i = 0; i < sizeof(struct ip_info); i++) { *dst++ = *src++; } }
/* 网络模块初始化 */ void sock_init(void) { struct socket *sock; int i; /* Set up our SOCKET VFS major device. */ /* 注册网络设备读写函数,在Linux系统当中所有的设备操作都被 * 当成对文件系统的操作 */ if (register_chrdev(SOCKET_MAJOR, "socket", &net_fops) < 0) { printk("NET: cannot register major device %d!\n", SOCKET_MAJOR); return; } /* Release all sockets. */ for (sock = sockets; sock <= last_socket; ++sock) sock->state = SS_FREE; /* Initialize all address (protocol) families. */ for (i = 0; i < NPROTO; ++i) pops[i] = NULL; /* Initialize the DDI module. */ /* 设备驱动接口模块 */ ddi_init(); /* Initialize the ARP module. */ #if 0 arp_init(); #endif }
void tcpipinit() { prog_name= "kernel TCP/IP"; mu_init(&mu_generic); mu_lock(&mu_generic); tcpip_dirinit(); sr_init_cap_names(); sr_set_cap_name(ETH_DEV0, "eth"); sr_set_cap_name(IP_DEV0, "ip"); sr_set_cap_name(TCP_DEV0, "tcp"); sr_set_cap_name(UDP_DEV0, "udp"); #if 0 sr_enable_linger_right(); #endif bf_init(); clck_init(); sr_init(); eth_init(); arp_init(); ip_init(); tcp_init(); udp_init(); add_default_gws(); mu_unlock(&mu_generic); tcpip_chmod(); }
int main(int argc, char** argv){ char buf[BUFLEN]; char *dev = calloc(10, 1); struct netdev netdev; CLEAR(buf); tun_init(dev); netdev_init(&netdev, "10.0.0.4", "00:0c:29:6d:50:25"); arp_init(); while(1) { if (tun_read(buf, BUFLEN) < 0) { print_error("ERR: Read from tun_fd: %s\n", strerror(errno)); } print_hexdump(buf, BUFLEN); struct eth_hdr *hdr = init_eth_hdr(buf); handle_frame(&netdev, hdr); } }
int microps_init (void) { if (ethernet_init() == -1) { goto ERROR; } if (slip_init() == -1) { goto ERROR; } if (arp_init() == -1) { goto ERROR; } if (ip_init() == -1) { goto ERROR; } if (icmp_init() == -1) { goto ERROR; } if (udp_init() == -1) { goto ERROR; } if (tcp_init() == -1) { goto ERROR; } return 0; ERROR: microps_cleanup(); return -1; }
void net_init(void) { static int first_call = 1; if (first_call) { /* * Setup packet buffers, aligned correctly. */ int i; net_tx_packet = &net_pkt_buf[0] + (PKTALIGN - 1); net_tx_packet -= (ulong)net_tx_packet % PKTALIGN; for (i = 0; i < PKTBUFSRX; i++) { net_rx_packets[i] = net_tx_packet + (i + 1) * PKTSIZE_ALIGN; } arp_init(); net_clear_handlers(); /* Only need to setup buffer pointers once. */ first_call = 0; } net_init_loop(); }
int microps_init (const struct microps_param *param) { if (ethernet_init() == -1) { goto ERROR; } if (ethernet_device_open(param->ethernet_device, param->ethernet_addr) == -1) { goto ERROR; } if (arp_init() == -1) { goto ERROR; } if (ip_init(param->ip_addr, param->ip_netmask, param->ip_gateway) == -1) { goto ERROR; } if (icmp_init() == -1) { goto ERROR; } if (udp_init() == -1) { goto ERROR; } if (tcp_init() == -1) { goto ERROR; } if (ethernet_device_run() == -1) { goto ERROR; } return 0; ERROR: //microps_cleanup(); return -1; }
void net_init(mbi_t *mbi) { net_info_t *net = &info->hrd.dev.net; net_init_arch(net); net_params(mbi); arp_init(); }
//------------------------------------------------------------------------------ int main(void) { tOplkError ret = kErrorOk; const UINT8 aMacAddr[] = {MAC_ADDR}; UINT8 nodeid; // Initialize helper modules gpio_init(); lcd_init(); // get node ID from input nodeid = gpio_getNodeid(); // initialize instance memset(&instance_l, 0, sizeof(instance_l)); instance_l.cycleLen = CYCLE_LEN; instance_l.nodeId = (nodeid != 0) ? nodeid : NODEID; instance_l.fShutdown = FALSE; instance_l.fGsOff = FALSE; // set mac address (last byte is set to node ID) memcpy(instance_l.aMacAddr, aMacAddr, sizeof(aMacAddr)); instance_l.aMacAddr[5] = instance_l.nodeId; initEvents(&eventCbPowerlink); arp_init((UINT8)instance_l.nodeId); PRINTF("----------------------------------------------------\n"); PRINTF("openPOWERLINK embedded CN DEMO application\n"); PRINTF("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION); PRINTF("----------------------------------------------------\n"); PRINTF("NODEID=0x%02X\n", instance_l.nodeId); lcd_printNodeId(instance_l.nodeId); if ((ret = initPowerlink(&instance_l)) != kErrorOk) goto Exit; if ((ret = initApp()) != kErrorOk) goto Exit; if ((ret = oplk_setNonPlkForward(TRUE)) != kErrorOk) goto Exit; loopMain(&instance_l); Exit: arp_exit(); shutdownPowerlink(&instance_l); shutdownApp(); // Shutdown helper modules lcd_exit(); gpio_exit(); return 0; }
void net_init (void) { int32 nbufs; /* Total no of buffers */ /* Initialize the network data structure */ memset((char *)&NetData, NULLCH, sizeof(struct network)); /* Obtain the Ethernet MAC address */ control(ETHER0, ETH_CTRL_GET_MAC, (int32)NetData.ethucast, 0); memset((char *)NetData.ethbcast, 0xFF, ETH_ADDR_LEN); /* Initialize the random port seed */ netportseed = getticks(); /* Create the network buffer pool */ nbufs = UDP_SLOTS * UDP_QSIZ + ICMP_SLOTS * ICMP_QSIZ + 1; netbufpool = mkbufpool(PACKLEN, nbufs); /* Initialize the ARP cache */ arp_init(); /* Initialize UDP */ udp_init(); /* Initialize ICMP */ icmp_init(); /* Initialize the IP output queue */ ipoqueue.iqhead = 0; ipoqueue.iqtail = 0; ipoqueue.iqsem = semcreate(0); if((int32)ipoqueue.iqsem == SYSERR) { panic("Cannot create ip output queue semaphore"); return; } /* Create the IP output process */ resume(create(ipout, NETSTK, NETPRIO, "ipout", 0, NULL)); /* Create a network input process */ resume(create(netin, NETSTK, NETPRIO, "netin", 0, NULL)); }
static status_t arp_std_ops(int32 op, ...) { switch (op) { case B_MODULE_INIT: return arp_init(); case B_MODULE_UNINIT: return arp_uninit(); default: return B_ERROR; } }
/* 1. 向全局协议簇数组中,注册协议簇 proto_ops结构 * 2. 向全局传输层协议链表中,注册传输层协议 proto结构 * 3. 初始化arp模块 向全局变量ptype_base中注册处理函数,供链路层向上传递数据 注册定时时间,清理arp项过期 * 4. 初始化ip模块 向全局变量ptype_base中注册处理函数,供链路层向上传递数据 */ void inet_proto_init(struct net_proto *pro) { struct inet_protocol *p; int i; printk("Swansea University Computer Society TCP/IP for NET3.019\n"); /* * Tell SOCKET that we are alive... * 向SOCKET模块注册协议簇 */ (void) sock_register(inet_proto_ops.family, &inet_proto_ops); seq_offset = CURRENT_TIME*250; /* * Add all the protocols. */ for(i = 0; i < SOCK_ARRAY_SIZE; i++) { tcp_prot.sock_array[i] = NULL; udp_prot.sock_array[i] = NULL; raw_prot.sock_array[i] = NULL; } tcp_prot.inuse = 0; tcp_prot.highestinuse = 0; udp_prot.inuse = 0; udp_prot.highestinuse = 0; raw_prot.inuse = 0; raw_prot.highestinuse = 0; printk("IP Protocols: "); for(p = inet_protocol_base; p != NULL;) { struct inet_protocol *tmp = (struct inet_protocol *) p->next; inet_add_protocol(p); printk("%s%s",p->name,tmp?", ":"\n"); p = tmp; } /* * Set the ARP module up */ arp_init(); /* * Set the IP module up */ ip_init(); }
PRIVATE void nw_init() { mq_init(); qp_init(); bf_init(); clck_init(); sr_init(); eth_init(); arp_init(); psip_init(); ip_init(); tcp_init(); udp_init(); }
//ONLY ONE INSTANCE FOR ALL POSSIBLE INTERFACES!!!!! t_network_desc* network_init() { t_network_desc* network_desc; network_desc=kmalloc(sizeof(t_network_desc)); network_desc->tx_queue=sckt_buf_desc_init(); network_desc->rx_queue=sckt_buf_desc_init(); network_desc->dev=init_8254x(); network_desc->ip=LOCAL_IP; network_desc->netmask=LOCAL_NETMASK; network_desc->default_gw_ip=DEFAULT_GW_IP; network_desc->socket_desc=socket_desc_init(); arp_init(); return network_desc; }
int net_init() /* The order in which the init routines are called is important. */ { extern int arp_init(void); extern int ip_init(void); #ifdef ASH_NET extern void ae_eth_init(void); ae_eth_init(); #endif /* printf("Net Init: "); */ ip_init(); arp_init(); return(0); }
PRIVATE void nw_init() { #if DEBUG & 256 { where(); printf("starting mq_init()\n"); } #endif mq_init(); #if DEBUG & 256 { where(); printf("starting bf_init()\n"); } #endif bf_init(); #if DEBUG & 256 { where(); printf("starting clck_init()\n"); } #endif clck_init(); #if DEBUG & 256 { where(); printf("starting sr_init()\n"); } #endif sr_init(); #if DEBUG & 256 { where(); printf("starting eth_init()\n"); } #endif eth_init(); #if DEBUG & 256 { where(); printf("starting arp_init()\n"); } #endif #if ENABLE_ARP arp_init(); #endif #if DEBUG & 256 { where(); printf("starting ip_init()\n"); } #endif #if ENABLE_IP ip_init(); #endif #if DEBUG & 256 { where(); printf("starting tcp_init()\n"); } #endif #if ENABLE_TCP tcp_init(); #endif #if DEBUG & 256 { where(); printf("starting udp_init()\n"); } #endif #if ENABLE_UDP udp_init(); #endif }
void net_init (void) { int32 iface; /* index into interface table */ char str[16]; /* string to hold process name */ /* Initialize interface data structures */ netiface_init(); /* Initialize ARP cache for each interface */ for (iface=0; iface<NIFACES; iface++) { arp_init(iface); } /* Initialize UDP */ udp_init(); /* Initialize ICMP */ icmp_init(); /* Create a network input process for each interface */ for (iface=0; iface<NIFACES; iface++) { sprintf(str, "net%d_input", iface); resume(create(netin, 4196, 5000, str, 1, iface)); } /* Initialize the IP output queue */ ipoqueue.iqtail = ipoqueue.iqhead = 0; ipoqueue.iqsem = semcreate(0); /* Create an IP output process */ resume(create(ipout, 2048, 6000, "ip_output", 0)); /* Create a low-level input process that reads raw frames and */ /* demultiplexes them to the correct interface */ resume(create(rawin, 2048, 8000, "raw_input", 0)); }
/*-----------------------------------------------------------------------------------*/ void tapif_init(struct netif *netif) { struct tapif *tapif; tapif = mem_malloc(sizeof(struct tapif)); netif->state = tapif; netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; netif->output = tapif_output; netif->linkoutput = low_level_output; tapif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]); low_level_init(netif); arp_init(); /*sys_timeout(ARP_TMR_INTERVAL, (sys_timeout_handler)arp_timer, NULL);*/ }
void uos_init (void) { /* Configure 16 Mbyte of external Flash memory at nCS3. */ MC_CSCON3 = MC_CSCON_WS (4); /* Wait states */ /* Выделяем место для динамической памяти */ extern unsigned __bss_end[]; #ifdef ELVEES_DATA_SDRAM /* Динамическая память в SDRAM */ if (((unsigned) __bss_end & 0xF0000000) == 0x80000000) mem_init (&pool, (unsigned) __bss_end, 0x82000000); else mem_init (&pool, (unsigned) __bss_end, 0xa2000000); #else /* Динамическая память в CRAM */ extern unsigned _estack[]; mem_init (&pool, (unsigned) __bss_end, (unsigned) _estack - 256); #endif timer_init (&timer, KHZ, 20); /* * Create a group of two locks: timer and eth. */ mutex_group_t *g = mutex_group_init (group, sizeof(group)); mutex_group_add (g, ð->netif.lock); mutex_group_add (g, &timer.decisec); arp = arp_init (arp_data, sizeof(arp_data), &ip); ip_init (&ip, &pool, 70, &timer, arp, g); /* * Create interface eth0 */ const unsigned char my_macaddr[] = { 0, 9, 0x94, 0xf1, 0xf2, 0xf3 }; eth_init (eth, "eth0", 80, &pool, arp, my_macaddr); unsigned char my_ip[] = { 172, 0, 0, 18 }; route_add_netif (&ip, &route, my_ip, 24, ð->netif); h_udp_task = task_create (udp_task, 0, "udp", 65, stack_udp, sizeof (stack_udp)); init_trace(); }
//------------------------------------------------------------------------- int _start(int argc, char *argv[]) { // Init SMAP if (smap_init(&g_param.eth_addr_src[0]) != 0) return MODULE_NO_RESIDENT_END; // Does ARP request and wait reply to get server MAC address arp_init(&g_param); #ifdef UDPTTY // Init UDP tty ttyInit(&g_param); #endif // Init TCPIP layer tcp_init(&g_param); tcp_connect(); return MODULE_RESIDENT_END; }
void uos_init (void) { printf (&debug, "\nCPU speed is %d MHz\n", KHZ/1000); /* Используем только внутреннюю память. * Оставляем 256 байтов для задачи "idle". */ extern unsigned __bss_end[], _estack[]; mem_init (&pool, (unsigned) __bss_end, (unsigned) _estack - 256); timer_init (&timer, KHZ, 50); gpanel_init (&display, &font_fixed6x8); gpanel_clear (&display, 0); puts (&display, "Testing TCP.\r\n"); /* * Create a group of two locks: timer and eth. */ mutex_group_t *g = mutex_group_init (group, sizeof(group)); mutex_group_add (g, ð.netif.lock); mutex_group_add (g, &timer.decisec); arp = arp_init (arp_data, sizeof(arp_data), &ip); ip_init (&ip, &pool, 70, &timer, arp, g); /* * Create interface eth0 */ const unsigned char my_macaddr[] = { 0, 9, 0x94, 0xf1, 0xf2, 0xf3 }; k5600bg1_init (ð, "eth0", 80, &pool, arp, my_macaddr); unsigned char my_ip[] = { 192, 168, 20, 222 }; route_add_netif (&ip, &route, my_ip, 24, ð.netif); task_create (tcp_task, 0, "tcp", 20, stack_tcp, sizeof (stack_tcp)); // task_create (poll_task, 0, "poll", 1, // stack_poll, sizeof (stack_poll)); task_create (console_task, 0, "cons", 10, stack_console, sizeof (stack_console)); }
void inet_proto_init(struct net_proto *proto) { int i; struct inet_protocol *p; (void)sock_register(inet_protocol.family,&inet_protocol); for(i = 0;i < SOCK_ARRAY_SIZE;i++) { tcp_prot.sock_array[i] = NULL; udp_prot.sock_array[i] = NULL; raw_prot.sock_array[i] = NULL; } tcp_prot.inuse = 0; tcp_prot.highestinuse = 0; udp_prot.inuse = 0; udp_prot.highestinuse = 0; raw_prot.inuse = 0; raw_prot.highestinuse = 0; printk("IP Protocols:\n"); for(p = inet_protocol_base ; p!=NULL; ) { struct inet_protocol *tmp = p->next; inet_add_protocol(p); printk("%s%s",p->name,tmp?",":"\n"); } arp_init(); ip_init(); return; }
//------------------------------------------------------------------------------ int main(void) { tOplkError ret = kErrorOk; const UINT8 aMacAddr[] = {MAC_ADDR}; UINT8 nodeid; #if (CONFIG_CDC_ON_SD != FALSE) tCdcBuffInfo cdcBuffInfo; #endif // Initialize helper modules gpio_init(); lcd_init(); // get node ID from input nodeid = gpio_getNodeid(); // initialize instance memset(&instance_l, 0, sizeof(instance_l)); instance_l.cycleLen = CYCLE_LEN; instance_l.nodeId = (nodeid != 0) ? nodeid : NODEID; instance_l.fShutdown = FALSE; instance_l.fGsOff = FALSE; #if (CONFIG_CDC_ON_SD != FALSE) if (sdcard_getCdcOnSd(pszCdcFilename_g, &cdcBuffInfo) != 0) { goto Exit; } instance_l.pCdcBuffer = (unsigned char*)cdcBuffInfo.pCdcBuffer; instance_l.cdcBufferSize = cdcBuffInfo.cdcSize; #else instance_l.pCdcBuffer = (unsigned char*)aCdcBuffer; instance_l.cdcBufferSize = sizeof(aCdcBuffer); #endif // set mac address (last byte is set to node ID) memcpy(instance_l.aMacAddr, aMacAddr, sizeof(aMacAddr)); instance_l.aMacAddr[5] = instance_l.nodeId; initEvents(&instance_l.fGsOff, &eventCbPowerlink); arp_init((UINT8)instance_l.nodeId); PRINTF("----------------------------------------------------\n"); PRINTF("openPOWERLINK console MN DEMO application\n"); PRINTF("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION); PRINTF("----------------------------------------------------\n"); PRINTF("NODEID=0x%02X\n", instance_l.nodeId); lcd_printNodeId(instance_l.nodeId); if ((ret = initPowerlink(&instance_l)) != kErrorOk) goto Exit; if ((ret = initApp()) != kErrorOk) goto Exit; if ((ret = oplk_setNonPlkForward(TRUE)) != kErrorOk) goto Exit; loopMain(&instance_l); Exit: #if (CONFIG_CDC_ON_SD != FALSE) sdcard_freeCdcBuffer(&cdcBuffInfo); #endif arp_exit(); shutdownPowerlink(&instance_l); shutdownApp(); // Shutdown helper modules lcd_exit(); gpio_exit(); return 0; }
process netin(void) { status retval; /* return value from function */ recv_packets = 0; /* initialize */ netbufpool = mkbufpool(PACKLEN, UDP_SLOTS * UDP_QSIZ + ICMP_SLOTS * ICMP_QSIZ + ICMP_OQSIZ + 1); if (netbufpool == SYSERR) { kprintf("Cannot allocate network buffer pool"); kill(getpid()); } /* Copy Ethernet address to global variable */ control(ETHER0, ETH_CTRL_GET_MAC, (int32)NetData.ethaddr, 0); /* Indicate that IP address, mask, and router are not yet valid */ NetData.ipvalid = FALSE; NetData.ipaddr = 0; NetData.addrmask = 0; NetData.routeraddr = 0; /* Initialize ARP cache */ arp_init(); /* Initialize UDP table */ udp_init(); currpkt = (struct netpacket *)getbuf(netbufpool); /* Do forever: read packets from the network and process */ //kprintf("[netin]: start to read packets\r\n"); while(1) { retval = read(ETHER0, (char *)currpkt, PACKLEN); if (retval == SYSERR) { panic("Ethernet read error"); } /* Convert Ethernet Type to host order */ eth_ntoh(currpkt); /* Demultiplex on Ethernet type */ switch (currpkt->net_ethtype) { case ETH_ARP: arp_in(); /* Handle an ARP packet */ continue; case ETH_IP: /* Convert IP packet to host order */ if (ipcksum(currpkt) != 0) { kprintf("checksum failed\n\r"); continue; } if (currpkt->net_ipvh != 0x45) { kprintf("version failed\n\r"); continue; } /* Convert IP packet to host byte order */ ip_ntoh(currpkt); if ( (currpkt->net_ipdst != IP_BCAST) && (NetData.ipvalid) && (currpkt->net_ipdst != NetData.ipaddr) ) { continue; } /* Demultiplex UDP and ignore others */ if (currpkt->net_ipproto == IP_UDP) { //kprintf("[netin]: UDP# %d\r\n", ++recv_packets); udp_in();/* Handle a UDP packet */ } continue; default: /* Ignore all other Ethernet types */ kprintf("\n"); continue; } } }
int main(int argc, char *argv[]) { dhcpctl_handle conn = NULL; char *conffile=NULL; char ch; name = strdup("OMAPI"); openlog("dhcparpd", LOG_PID, LOG_DAEMON); /* Parse Commandline Options */ while((ch = getopt(argc, argv, "c:dh")) != -1) { switch(ch){ case 'c': conffile = strdup(optarg); break; case 'd': do_daemonise=0; break; case 'h': usage(argv[0]); return 0; default: fprintf(stderr, "Unknown option '%c'!", ch); usage(argv[0]); return 1; } } /* Try a default configfile if non specified */ if (conffile==NULL) { conffile = strdup("/etc/dhcparpd.conf"); } if (parse_config(config,conffile)) { fprintf(stderr,"Unable to parse configfile: %s\n", conffile); return 1; } free(conffile); /* Daemonise */ if (do_daemonise) { daemonise(argv[0]); put_pid(pidfile); } parse_mappings(); conn = dhcpd_connect(servername, port, name, key); if (!conn) { Log(LOG_CRIT, "failed to connect to dhcp server"); return 1; } arp_init(interface,conn); init_event(); init_netlink(); if (pcap_init(interface)) return 1; Log(LOG_NOTICE, "Ready for action! Lets Go..."); run(); return 0; }
int main(void) { /* constants */ const ethernet_address my_mac = {'<','P','A','K','O','>'}; /* init io */ DDRB = 0xff; PORTB = 0xff; DDRE &= ~(1<<7); PORTE |= (1<<7); /* init interrupts */ interrupt_timer0_init(); interrupt_timer1_init(); interrupt_exint_init(); /* init arch */ uart_init(); spi_init(); i2c_init(); timer_init(); DBG_INFO("\n\n"); DBG_INFO(B_IBLUE "avr-net ver %s build time: %s %s\n","1.0",__DATE__,__TIME__); /* init utils */ fifo_init(); /* init dev */ uint8_t ret = ds1338_init(); DBG_INFO("ds1338_init ret = 0x%x\n",ret); enc28j60_init((uint8_t*)&my_mac); /* init sys */ // fat_init(); //rtc_init((0<<RTC_FORMAT_12_24)|(0<<RTC_FORMAT_AM_PM)); ethernet_init(&my_mac); const ip_address ip = NET_IP_ADDRESS; const ip_address gw = NET_IP_GATEWAY; const ip_address nm = NET_IP_NETMASK; ip_init(&ip, &nm, &gw); // ip_init(0,0,0); arp_init(); udp_init(); // tcp_init(); // echod_start(); stdout = DEBUG_FH; // sd_init(sdcallback); // sd_interrupt(); // httpd_start(); dhcp_start(dhcp_callback); // netstat(stdout, NETSTAT_OPT_ALL); // timer_t timer = timer_alloc(timer_callback); // timer_set(timer, 5000, TIMER_MODE_PERIODIC); // DBG_INFO("Before sei\n"); /* global interrupt enable */ sei(); for(;;) { } return 0; }
static int setup (void) { ethernet_init(); arp_init(); return 0; }
int main(void) { t_addr *pkt; struct net_iface iface; struct ether_header *reth; struct ether_arp *rarp; unsigned char dest_mac[6]; unsigned char dest_ip[4]; //u_int16_t ethtype; //#ifndef DEBUG // t_addr* next_packet; // int i=nf_tid(); // // if(i== 0) // { // nf_lock(LOCK_INIT); // should get it on the first attempt // nf_pktout_init(); // nf_pktin_init(); // } // else // { // nf_stall_a_bit(); // nf_lock(LOCK_INIT); // should not get it // } // nf_unlock(LOCK_INIT); // //#endif //test_this(); // iface is not shared, it's on the stack arp_init(&iface.arp); iface.mac[0] = 0x00; iface.mac[1] = 0x43; iface.mac[2] = 0x32; iface.mac[3] = 0x46; iface.mac[4] = 0x4e; iface.mac[5] = 0x00; iface.ip[0] = 192; iface.ip[1] = 168; iface.ip[2] = 0; iface.ip[3] = 100; //dest_mac[0] = 0x70; //dest_mac[1] = 0x56; //dest_mac[2] = 0x81; //dest_mac[3] = 0xa9; //dest_mac[4] = 0x2c; //dest_mac[5] = 0x39; dest_mac[0] = 0xff; dest_mac[1] = 0xff; dest_mac[2] = 0xff; dest_mac[3] = 0xff; dest_mac[4] = 0xff; dest_mac[5] = 0xff; dest_ip[0] = 192; dest_ip[1] = 168; dest_ip[2] = 0; dest_ip[3] = 185; //ethtype = ETHERTYPE_ARP; //only run this program on thread 0 if (nf_tid() != 0) { while (1) {} } // initialize nf_pktout_init(); nf_pktin_init(); // allocate an output buffer pkt = nf_pktout_alloc(PKT_SIZE); // setup the ioq_header fill_ioq((struct ioq_header*) pkt, 2, PKT_SIZE); // setup the ethernet header //struct ether_header *reth = (struct ether_header*) (pkt + sizeof(struct ioq_header)); reth = (struct ether_header*) (pkt + sizeof(struct ioq_header)); // setup the ethernet arp //struct ether_arp *rarp = (struct ether_arp*) (pkt + sizeof(struct ioq_header) + sizeof(struct ether_header)); rarp = (struct ether_arp*) (pkt + sizeof(struct ioq_header) + sizeof(struct ether_header)); // start putting things into the packet // ethernet memcpy(reth->ether_shost, &iface.mac, ETH_ALEN); memcpy(reth->ether_dhost, &dest_mac, ETH_ALEN); //memcpy(reth->ether_type, htons(ethtype), sizeof(u_int16_t)); //memcpy(reth->ether_type, ðtype, 2); //memcpy(reth->ether_type, &mytype, 2); reth->ether_type = ETHERTYPE_ARP; // arp header rarp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER); rarp->ea_hdr.ar_pro = htons(ETHERTYPE_IP); //rarp->ea_hdr.ar_pro = htons(0x0800); rarp->ea_hdr.ar_hln = 6; rarp->ea_hdr.ar_pln = 4; rarp->ea_hdr.ar_op = htons(ARPOP_REQUEST); // arp ethernet // source memcpy(rarp->arp_sha, &iface.mac, ETH_ALEN); memcpy(rarp->arp_spa, &iface.ip, 4); // target memcpy(rarp->arp_tha, dest_mac, ETH_ALEN); memcpy(rarp->arp_tpa, dest_ip, 4); // send it nf_pktout_send(pkt, pkt + PKT_SIZE); nf_pktout_send(pkt, pkt + PKT_SIZE); nf_pktout_send(pkt, pkt + PKT_SIZE); nf_pktout_send(pkt, pkt + PKT_SIZE); //free //nf_pktin_free(pkt); // start in on replying //while(1) //{ // pkt = nf_pktin_pop(); // test for next_packet // if(!nf_pktin_is_valid(pkt)) // continue; // process_eth(&iface, pkt); // nf_pktin_free(pkt); //} //memcpy(reply.data, pkt->head, pkt->len); //struct ioq_header *reply_ioq = pkt_pull(&reply, sizeof(struct ioq_header)); //fill_ioq(reply_ioq, ioq->src_port, reply.len); //struct ether_header *reply_ether = pkt_pull(&reply, sizeof(struct ether_header)); //struct ether_arp *reply_arp = pkt_pull(&reply, sizeof(struct ether_arp)); // copy source ip and mac to target //memcpy(reply_arp->arp_tha, reply_arp->arp_sha, ETH_ALEN); //memcpy(reply_arp->arp_tpa, reply_arp->arp_spa, 4); // copy this interface's mac and ip to source //memcpy(reply_arp->arp_sha, iface->mac, ETH_ALEN); //memcpy(reply_arp->arp_spa, iface->ip, 4); //reply_arp->ea_hdr.ar_op = htons(ARPOP_REPLY); //memcpy(reply_ether->ether_shost, iface->mac, ETH_ALEN); //memcpy(reply_ether->ether_dhost, reply_arp->arp_tha, ETH_ALEN); //pkt_push_all(&reply); //send_pkt(reply.data, reply.len); return 0; }
/* *Init a etherner interface. * *@param eth_if, if hander. * *@return err code. * **/ err_t ethernetif_initParams(Netif_t *eth_if, char *mac, char *ip, char *gatway, char *mask, err_t (*low_output)(U8_t *,U32_t )){ //初始化 网络接口类型 eth_if->If = IFTYPE_ETHERNET; //网络接口 硬件地址长度 eth_if->haLen = 6; //网络接口 协议地址长度 eth_if->paLen = 4; //协议地址的 类型 eth_if->paType = PROTYPE_IP; //当前处理的协议栈 位置,即当前协议名称 eth_if->pType = PROTYPE_UNKNOWN; //复制传入硬件地址 memcpy(eth_if->hAddr, mac, eth_if->haLen); //复制传入协议地址 n2IP_IPv4Cast(eth_if->pAddr, ip); //复制网关的协议地址 n2IP_IPv4Cast(eth_if->pgAddr, gatway); //复制网关协议地址 n2IP_IPv4Cast(eth_if->pmAddr, mask); //赋值 底层输出函数, 一般连接网卡驱动层 eth_if->low_output = low_output; //底层输入函数, 连接网卡驱动层 eth_if->low_input = ethernet_poll; //从网络接入层提交到TCP/IP协议栈中,即n2IP内核中 eth_if->poll = n2IP_poll; //从TCP/IP协议栈 输出数据到网络接口层 eth_if->drag = ethernetif_drag; /*以下元素 是kernel能完整传递不同 层数据同时保证层间松耦合性的关键, *由netif只传递数据的指针,而不是发生上下文的拷贝;如果需要回溯数据内容, *直接由额外的指针索引。 **/ //输入数据 句柄 eth_if->inBuf = NULL; //输入数据 大小 eth_if->ibSize = 0; //输出数据 大小 eth_if->obSize = 0; //输出数据 句柄 eth_if->outBuf = NULL; //show the log info of the if. ethernetif_show(eth_if); //init ids. eth_if->ip_id = 0x01; eth_if->icmp_id = 0x01; //进行必要的初始化步骤 //初始化netif的arp表项 eth_if->arp_size = ARP_CACHE_MAX_ENTRY; arp_init(eth_if); //初始化netif的udp表项 eth_if->ucb_size = UDP_SOCKET_MAX_SIZE; udp_init(eth_if); return ERR_NONE; }
int main(int argc, char **argv) { char dev_if[16]; int opt; int err = 0; int daemonize = 0; int log_level = LOG_WARN; char *log_file = NULL; memset(dev_if, '\0', sizeof(dev_if)); strncpy(dev_if, PHOST_DEFAULT_TAP_DEVICE, sizeof(dev_if) - 1); phost_set_program_name(basename(argv[0])); /* parse options */ while(1){ opt = getopt(argc, argv, "Dd:i:p:l:n:v"); if(opt < 0){ break; } switch(opt){ case 'D': daemonize = 1; break; case 'd': if(optarg){ if(atoi(optarg) < LOG_LEVEL_MAX){ log_level = atoi(optarg); } else{ phost_print_usage(); exit(1); } } else{ err |= 1; } break; case 'i': if(optarg){ memset(dev_if, '\0', sizeof(dev_if)); strncpy(dev_if, optarg, sizeof(dev_if) - 1); } else{ err |= 1; } break; case 'p': if(optarg){ memset(pid_dir, '\0', sizeof(pid_dir)); strncpy(pid_dir, optarg, sizeof(pid_dir) - 1); } else{ err |= 1; } break; case 'l': if(optarg){ memset(log_dir, '\0', sizeof(log_dir)); strncpy(log_dir, optarg, sizeof(log_dir) - 1); } else{ err |= 1; } break; case 'n': if(optarg){ memset(host_name, '\0', sizeof(host_name)); strncpy(host_name, optarg, sizeof(host_name) - 1); } else{ err |= 1; } break; case 'v': log_file = LOG_OUT_STDOUT; log_level = LOG_DEBUG; break; default: err |= 1; } } if(err){ phost_print_usage(); exit(1); } if(log_file == NULL){ log_file = (char*)malloc(sizeof(char)*(strlen(log_dir)+strlen(PHOST_LOG_FILE)+strlen(dev_if)+3)); sprintf(log_file, "%s/%s.%s", log_dir, PHOST_LOG_FILE, dev_if); } /* check if this process is run with root privilege */ if(getuid() != 0){ fprintf(stderr, "[ERROR] `%s' must be run with root privilege.\n", program_name); exit(1); } /* register signal handler */ signal(SIGINT, phost_handle_signals); signal(SIGTERM, phost_handle_signals); signal(SIGPIPE, SIG_IGN); signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); /* initializations */ if(log_init(log_level, log_file) < 0){ fprintf(stderr, "[ERROR] cannot initialize logger.\n"); exit(1); } if(daemonize && (phost_daemonize() < 0)){ fprintf(stderr, "[ERROR] cannot daemonize.\n"); exit(1); } if(strncmp(dev_if, "tap", 3) != 0){ if(ethdev_init(dev_if) < 0){ fprintf(stderr, "[ERROR] cannot initialize Ethernet device (%s).\n", dev_if); exit(1); } trx_init(ethdev_read, ethdev_send); } else{ if(tap_init(dev_if) < 0){ fprintf(stderr, "[ERROR] cannot create tap device (%s).\n", dev_if); exit(1); } trx_init(tap_read, tap_send); } phost_set_global_params(); phost_create_pid_file(host_name); cmdif_init(dev_if, stats_udp_send_update); arp_init(host_mac_addr, host_ip_addr); ipv4_init(host_ip_addr, host_ip_mask); udp_init(stats_udp_recv_update); pkt_dump = (char*)malloc(sizeof(char)*PKT_BUF_SIZE*2); while(run){ phost_run(); cmdif_run(); arp_age_entries(); } free(pkt_dump); cmdif_close(); tap_close(); phost_delete_pid_file(host_name); phost_unset_global_params(); log_close(); return 0; }