// constructor lwip.slip(device=integer, iplocal=string, ipremote=string) STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 3, 3, false); lwip_slip_obj.base.type = &lwip_slip_type; MP_STATE_VM(lwip_slip_stream) = args[0]; ip_addr_t iplocal, ipremote; if (!ipaddr_aton(mp_obj_str_get_str(args[1]), &iplocal)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "not a valid local IP")); } if (!ipaddr_aton(mp_obj_str_get_str(args[2]), &ipremote)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "not a valid remote IP")); } struct netif *n = &lwip_slip_obj.lwip_netif; if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "out of memory")); } netif_set_up(n); netif_set_default(n); mod_lwip_register_poll(slip_lwip_poll, n); return (mp_obj_t)&lwip_slip_obj; }
void ntp_setup(void) { tv_t tv; tz_t tz; time_t sec; if(!network_init) return; if(ntp_init == 0) { ip_addr_t *addr = (ip_addr_t *)os_zalloc(sizeof(ip_addr_t)); ipaddr_aton("192.168.200.1", addr); sntp_setserver(1,addr); ipaddr_aton("192.168.200.240", addr); sntp_setserver(2,addr); sntp_init(); os_free(addr); ntp_init = 1; DEBUG_PRINTF("NTP:1\n"); } if(ntp_init == 1) { // they hard coded it to +8 hours from GMT sec = sntp_get_current_timestamp(); if(sec > 10) { ntp_init = 2; } } if(ntp_init == 2) { sntp_stop(); DEBUG_PRINTF("NTP:2\n"); // they return GMT + 8 sec = sec - (8UL * 3600UL); // we are GMT - 4 sec = sec - (4UL * 3600UL); tv.tv_sec = sec; tv.tv_usec = 0; tz.tz_minuteswest = 0; settimeofday(&tv, &tz); DEBUG_PRINTF("SEC:%ld\n",sec); DEBUG_PRINTF("TIME:%s\n", ctime(&sec)); ntp_init = 3; } }
/** * Send out an sntp request via raw API. * * @param arg is unused (only necessary to conform to sys_timeout) */ static void sntp_request(void *arg) { ip_addr_t sntp_server_address; err_t err; LWIP_UNUSED_ARG(arg); /* Initialize SNTP server address */ #if SNTP_SERVER_DNS err = dns_gethostbyname(sntp_server_addresses[sntp_current_server], &sntp_server_address, sntp_dns_found, NULL); if (err == ERR_INPROGRESS) { /* DNS request sent, wait for sntp_dns_found being called */ LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_request: Waiting for server address to be resolved.\n")); return; } #else /* SNTP_SERVER_DNS */ err = ipaddr_aton(sntp_server_addresses[sntp_current_server], &sntp_server_address) ? ERR_OK : ERR_ARG; #endif /* SNTP_SERVER_DNS */ if (err == ERR_OK) { sntp_send_request(&sntp_server_address); } else { /* address conversion failed, try another server */ LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_request: Invalid server address, trying next server.\n")); sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_try_next_server, NULL); } }
void set_if(char* netif_name, char* ip_addr, char* gw_addr, char* nm_addr) { struct ip_addr *ip; struct ip_addr addr; struct netif * netif = netif_list; if(strlen(netif_name) > sizeof(netif->name)) { printf("network interface name too long!\r\n"); return; } while(netif != NULL) { if(strncmp(netif_name, netif->name, sizeof(netif->name)) == 0) break; netif = netif->next; if( netif == NULL ) { printf("network interface: %s not found!\r\n", netif_name); return; } } ip = (struct ip_addr *)&addr; /* set ip address */ if ((ip_addr != NULL) && ipaddr_aton(ip_addr, &addr)) { netif_set_ipaddr(netif, ip); } /* set gateway address */ if ((gw_addr != NULL) && ipaddr_aton(gw_addr, &addr)) { netif_set_gw(netif, ip); } /* set netmask address */ if ((nm_addr != NULL) && ipaddr_aton(nm_addr, &addr)) { netif_set_netmask(netif, ip); } }
void set_dns(char* dns_server) { ip_addr_t *addr; if ((dns_server != RT_NULL) && ipaddr_aton(dns_server, addr)) { dns_setserver(0, addr); } }
void set_dns(char* dns_server) { struct ip_addr addr; if ((dns_server != NULL) && ipaddr_aton(dns_server, &addr)) { dns_setserver(0, &addr); } }
/** * Ascii internet address interpretation routine. * The value returned is in network order. * * @param cp IP address in ascii represenation (e.g. "127.0.0.1") * @return ip address in network order */ uint32_t ipaddr_addr(const char *cp) { ip_addr_t val; if (ipaddr_aton(cp, &val)) { return ip4_addr_get_u32(&val); } return IPADDR_NONE; }
/** * Ascii internet address interpretation routine. * The value returned is in network order. * * @param cp IP address in ascii represenation (e.g. "127.0.0.1") * @return ip address in network order */ u32_t ICACHE_FLASH_ATTR ipaddr_addr(const char *cp) { ip_addr_t val; if (ipaddr_aton(cp, &val)) { return ip4_addr_get_u32(&val); } return (IPADDR_NONE); }
int TftpClient::connect(char *host, u16_t port) { if(connected == true){ error(lwip_strerr(ERR_ISCONN), false); } ipaddr_aton(host, &rem_host); rem_port = port; return 0; }
static void ICACHE_FLASH_ATTR _network_config_address(void) { #if CONFIG_USE_DHCP #error Not implemented yet! #else wifi_set_opmode(STATIONAP_MODE); uint8_t ret; ret = wifi_station_dhcpc_stop(); if (!ret) os_printf("dhcpc stop failed\r\n"); ret = ipaddr_aton(CONFIG_NETWORK_IP_ADDRESS, &ip_info.ip); if (!ret) os_printf("network IP address parse failed\r\n"); ret = ipaddr_aton(CONFIG_NETWORK_NETMASK, &ip_info.netmask); if (!ret) os_printf("network mask parse failed\r\n"); ret = ipaddr_aton(CONFIG_NETWORK_GATEWAY, &ip_info.gw); if (!ret) os_printf("network gateway parse failed\r\n"); wifi_set_ip_info(STATION_IF, &ip_info); #endif }
LOCAL void ICACHE_FLASH_ATTR sntp_starts_here(){ ipaddr_aton("192.168.254.30", &NTP1); // sntp_setservername(0, ”bg.pool.ntp.org”); // set server 0 by domain name // sntp_setservername(1, ”us.pool.ntp.org”); // set server 0 by domain name sntp_setserver(0,NTP1); sntp_set_timezone(+2); sntp_init(); os_timer_disarm(&ds18b20_timer); os_timer_setfn(&ds18b20_timer, (os_timer_func_t *)sntp_cb, (void *)0); os_timer_arm(&ds18b20_timer, DELAY, 1); }
ICACHE_FLASH_ATTR void syslog_init(const char *server, const char *hostname) { sint8 rc; syslog_hostname = hostname; syslog_espconn.type = ESPCONN_UDP; syslog_espconn.state = ESPCONN_NONE; syslog_espconn.proto.udp = &syslog_espconn_udp; syslog_espconn.proto.udp->local_port = espconn_port(); syslog_espconn.proto.udp->remote_port = 514; /* syslog */ ipaddr_aton(server, syslog_espconn.proto.udp->remote_ip); rc = espconn_create(&syslog_espconn); }
static socket_error_t str2addr(const struct socket *sock, struct socket_addr *address, const char *addr) { socket_error_t err = SOCKET_ERROR_NONE; switch(sock->stack) { case SOCKET_STACK_LWIP_IPV4: { ip_addr_t a; if (ipaddr_aton(addr, &a) == -1) { err = SOCKET_ERROR_BAD_ADDRESS; } else { socket_addr_set_ipv4_addr(address, (uint32_t) a.addr); } break; } default: break; } return err; }
/** Start the http request after converting 'server_name' to ip address (DNS or address string) */ static err_t httpc_get_internal_dns(httpc_state_t* req, const char* server_name) { err_t err; LWIP_ASSERT("req != NULL", req != NULL); #if LWIP_DNS err = dns_gethostbyname(server_name, &req->remote_addr, httpc_dns_found, req); #else err = ipaddr_aton(server_name, &req->remote_addr) ? ERR_OK : ERR_ARG; #endif if (err == ERR_OK) { /* cached or IP-string */ err = httpc_get_internal_addr(req, &req->remote_addr); } else if (err == ERR_INPROGRESS) { return ERR_OK; } return err; }
/** The actual mail-sending function, called by smtp_send_mail and * smtp_send_mail_static after setting up the struct smtp_session. */ static err_t smtp_send_mail_alloced(struct smtp_session *s) { err_t err; struct altcp_pcb* pcb = NULL; ip_addr_t addr; LWIP_ASSERT("no smtp_session supplied", s != NULL); #if SMTP_CHECK_DATA /* check that body conforms to RFC: * - convert all single-CR or -LF in body to CRLF * - only 7-bit ASCII is allowed */ if (smtp_verify(s->to, s->to_len, 0) != ERR_OK) { err = ERR_ARG; goto leave; } if (smtp_verify(s->from, s->from_len, 0) != ERR_OK) { err = ERR_ARG; goto leave; } if (smtp_verify(s->subject, s->subject_len, 0) != ERR_OK) { err = ERR_ARG; goto leave; } #if SMTP_BODYDH if (s->bodydh == NULL) #endif /* SMTP_BODYDH */ { if (smtp_verify(s->body, s->body_len, 0) != ERR_OK) { err = ERR_ARG; goto leave; } } #endif /* SMTP_CHECK_DATA */ #if SMTP_COPY_AUTHDATA /* copy auth data, ensuring the first byte is always zero */ MEMCPY(s->auth_plain + 1, smtp_auth_plain + 1, smtp_auth_plain_len - 1); s->auth_plain_len = smtp_auth_plain_len; /* default username and pass is empty string */ s->username = s->auth_plain; s->pass = s->auth_plain; if (smtp_username != NULL) { s->username += smtp_username - smtp_auth_plain; } if (smtp_pass != NULL) { s->pass += smtp_pass - smtp_auth_plain; } #endif /* SMTP_COPY_AUTHDATA */ s->state = SMTP_NULL; s->timer = SMTP_TIMEOUT; #if LWIP_DNS err = dns_gethostbyname(smtp_server, &addr, smtp_dns_found, s); #else /* LWIP_DNS */ err = ipaddr_aton(smtp_server, &addr) ? ERR_OK : ERR_ARG; #endif /* LWIP_DNS */ if (err == ERR_OK) { pcb = smtp_setup_pcb(s, &addr); if (pcb == NULL) { err = ERR_MEM; goto leave; } err = altcp_connect(pcb, &addr, smtp_server_port, smtp_tcp_connected); if (err != ERR_OK) { LWIP_DEBUGF(SMTP_DEBUG_WARN_STATE, ("tcp_connect failed: %d\n", (int)err)); goto deallocate_and_leave; } } else if (err != ERR_INPROGRESS) { LWIP_DEBUGF(SMTP_DEBUG_WARN_STATE, ("dns_gethostbyname failed: %d\n", (int)err)); goto deallocate_and_leave; } return ERR_OK; deallocate_and_leave: if (pcb != NULL) { altcp_arg(pcb, NULL); altcp_close(pcb); } leave: smtp_free_struct(s); /* no need to call the callback here since we return != ERR_OK */ return err; }
/*-----------------------------------------------------------------------------------*/ int main(int argc, char **argv) { int ch; char ip_str[16] = {0}; /* startup defaults (may be overridden by one or more opts) */ #if LWIP_IPV4 IP_ADDR4(&gw, 192,168, 0,1); IP_ADDR4(&netmask, 255,255,255,0); IP_ADDR4(&ipaddr, 192,168, 0,2); #if LWIP_HAVE_SLIPIF IP_ADDR4(&gw_slip, 192,168, 2, 1); IP_ADDR4(&netmask_slip, 255,255,255,255); IP_ADDR4(&ipaddr_slip, 192,168, 2, 2); #endif #endif /* LWIP_IPV4 */ ping_flag = 0; /* use debug flags defined by debug.h */ debug_flags = LWIP_DBG_OFF; while ((ch = getopt_long(argc, argv, "dhg:i:m:p:", longopts, NULL)) != -1) { switch (ch) { case 'd': debug_flags |= (LWIP_DBG_ON|LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_FRESH|LWIP_DBG_HALT); break; case 'h': usage(); exit(0); break; #if LWIP_IPV4 case 'g': ipaddr_aton(optarg, &gw); break; case 'i': ipaddr_aton(optarg, &ipaddr); break; case 'm': ipaddr_aton(optarg, &netmask); break; #endif /* LWIP_IPV4 */ case 'p': ping_flag = !0; ipaddr_aton(optarg, &ping_addr); strncpy(ip_str,ipaddr_ntoa(&ping_addr),sizeof(ip_str)); ip_str[sizeof(ip_str)-1] = 0; /* ensure \0 termination */ printf("Using %s to ping\n", ip_str); break; default: usage(); break; } } argc -= optind; argv += optind; #ifdef PERF perf_init("/tmp/simhost.perf"); #endif /* PERF */ printf("System initialized.\n"); sys_thread_new("main_thread", main_thread, NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); pause(); return 0; }
/********************************************************************************************************* ** 函数名称: __tshellRoute ** 功能描述: 系统命令 "route" ** 输 入 : iArgC 参数个数 ** ppcArgV 参数表 ** 输 出 : ERROR ** 全局变量: ** 调用模块: *********************************************************************************************************/ INT __tshellRoute (INT iArgC, PCHAR *ppcArgV) { #define LW_RT_PRINT_SIZE 74 INT iError; FUNCPTR pfuncAddOrChange; PCHAR pcOpAddorChange; UINT uiFlag = 0; ip_addr_t ipaddr; CHAR cNetifName[IF_NAMESIZE]; if (iArgC == 1) { PCHAR pcBuffer; size_t stSize; size_t stOffset; UINT uiNumEntries; uiNumEntries = (UINT)__rtSafeRun((FUNCPTR)__rtEntryMaxNum, 0, 0, 0, 0, 0, 0); if (uiNumEntries == 0) { printf("no route entry.\n"); return (ERROR_NONE); } /* * 在 net safe 状态下不允许调用 printf 等使用 IO 的语句. 所以只能打印到缓冲区中, * 然后统一使用 IO 打印. */ stSize = LW_RT_PRINT_SIZE * uiNumEntries; pcBuffer = (PCHAR)__SHEAP_ALLOC(stSize); if (pcBuffer == LW_NULL) { fprintf(stderr, "system low memory.\n"); return (PX_ERROR); } /* * 打印 kernel route entry */ stOffset = 0; printf("kernel routing tables\n"); printf("Destination Gateway Mask Flag Interface\n"); __rtSafeRun((FUNCPTR)__rtTraversal, (void *)__rtEntryPrint, pcBuffer, (PVOID)stSize, &stOffset, 0, 0); if (stOffset > 0) { fwrite(pcBuffer, stOffset, 1, stdout); fflush(stdout); /* 这里必须确保输出完成 */ } /* * 打印 lwip build-in route entry */ stOffset = 0; printf("\nbuild-in routing tables\n"); printf("Destination Gateway Mask Flag Interface\n"); __rtSafeRun((FUNCPTR)__buildinRtPrint, pcBuffer, (PVOID)stSize, &stOffset, 0, 0, 0); if (stOffset > 0) { fwrite(pcBuffer, stOffset, 1, stdout); fflush(stdout); /* 这里必须确保输出完成 */ } __SHEAP_FREE(pcBuffer); return (ERROR_NONE); } else { /* 操作路由表 */ if (lib_strcmp(ppcArgV[1], "add") == 0) { pfuncAddOrChange = __rtAdd; pcOpAddorChange = "add"; } else if (lib_strcmp(ppcArgV[1], "change") == 0) { pfuncAddOrChange = __rtChange; pcOpAddorChange = "change"; } else { pfuncAddOrChange = LW_NULL; } if (pfuncAddOrChange && (iArgC == 6)) { /* 添加或者修改路由表 */ if (!ipaddr_aton(ppcArgV[3], &ipaddr)) { fprintf(stderr, "inet address format error.\n"); goto __error_handle; } if (lib_strcmp(ppcArgV[4], "if") == 0) { /* 使用 ifindex 查询网卡 */ INT iIndex = lib_atoi(ppcArgV[5]); if (if_indextoname(iIndex, cNetifName) == LW_NULL) { fprintf(stderr, "can not find net interface with ifindex %d.\n", iIndex); goto __error_handle; } } else if (lib_strcmp(ppcArgV[4], "dev") == 0) { lib_strlcpy(cNetifName, ppcArgV[5], IF_NAMESIZE); } else { fprintf(stderr, "net interface argument error.\n"); goto __error_handle; } if (lib_strcmp(ppcArgV[2], "-host") == 0) { /* 主机路由 */ uiFlag |= LW_RT_FLAG_H; } else if (lib_strcmp(ppcArgV[2], "-gw") == 0) { /* 设置网卡网关 */ uiFlag |= LW_RT_GW_FLAG_SET; pfuncAddOrChange = __rtSetGw; } else if (lib_strcmp(ppcArgV[2], "-net") != 0) { /* 非网络路由 */ fprintf(stderr, "route add must determine -host or -net.\n"); goto __error_handle; } iError = pfuncAddOrChange(&ipaddr, uiFlag, cNetifName); /* 操作路由表 */ if (iError >= 0) { printf("route %s %s successful.\n", ppcArgV[3], pcOpAddorChange); return (ERROR_NONE); } } else if (pfuncAddOrChange && (iArgC == 5)) { /* 设置默认网关 */ if (lib_strcmp(ppcArgV[2], "default") != 0) { goto __error_handle; } if (lib_strcmp(ppcArgV[3], "if") == 0) { /* 使用 ifindex 查询网卡 */ INT iIndex = lib_atoi(ppcArgV[4]); if (if_indextoname(iIndex, cNetifName) == LW_NULL) { fprintf(stderr, "can not find net interface with ifindex %d.\n", iIndex); goto __error_handle; } } else if (lib_strcmp(ppcArgV[3], "dev") == 0) { lib_strlcpy(cNetifName, ppcArgV[4], IF_NAMESIZE); } else { fprintf(stderr, "net interface argument error.\n"); goto __error_handle; } uiFlag |= LW_RT_GW_FLAG_DEFAULT; pfuncAddOrChange = __rtSetGw; iError = pfuncAddOrChange(&ipaddr, uiFlag, cNetifName); /* 设置默认路由出口 */ if (iError >= 0) { printf("default device set successful.\n"); return (ERROR_NONE); } } else if ((lib_strcmp(ppcArgV[1], "del") == 0) && iArgC == 3) {/* 删除一个路由表项 */ if (!ipaddr_aton(ppcArgV[2], &ipaddr)) { fprintf(stderr, "inet address format error.\n"); goto __error_handle; } iError = __rtDel(&ipaddr); if (iError >= 0) { printf("route %s delete successful.\n", ppcArgV[2]); return (ERROR_NONE); } } } __error_handle: fprintf(stderr, "argments error!\n"); return (-ERROR_TSHELL_EPARAM); }
/** * Send an SNTP request via sockets. * This is a very minimal implementation that does not fully conform * to the SNTPv4 RFC, especially regarding server load and error procesing. */ void sntp_request(void *arg) { int sock; struct sockaddr_in local; struct sockaddr_in to; int tolen; int size; int timeout; struct sntp_msg sntpmsg; ip_addr_t sntp_server_address; LWIP_UNUSED_ARG(arg); /* if we got a valid SNTP server address... */ if (ipaddr_aton(SNTP_SERVER_ADDRESS, &sntp_server_address)) { /* create new socket */ sock = lwip_socket(AF_INET, SOCK_DGRAM, 0); if (sock >= 0) { /* prepare local address */ memset(&local, 0, sizeof(local)); local.sin_family = AF_INET; local.sin_port = PP_HTONS(INADDR_ANY); local.sin_addr.s_addr = PP_HTONL(INADDR_ANY); /* bind to local address */ if (lwip_bind(sock, (struct sockaddr *)&local, sizeof(local)) == 0) { /* set recv timeout */ timeout = SNTP_RECV_TIMEOUT; lwip_setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); /* prepare SNTP request */ sntp_initialize_request(&sntpmsg); /* prepare SNTP server address */ memset(&to, 0, sizeof(to)); to.sin_family = AF_INET; to.sin_port = PP_HTONS(SNTP_PORT); inet_addr_from_ipaddr(&to.sin_addr, &sntp_server_address); /* send SNTP request to server */ if (lwip_sendto(sock, &sntpmsg, SNTP_MSG_LEN, 0, (struct sockaddr *)&to, sizeof(to)) >= 0) { /* receive SNTP server response */ tolen = sizeof(to); size = lwip_recvfrom(sock, &sntpmsg, SNTP_MSG_LEN, 0, (struct sockaddr *)&to, (socklen_t *)&tolen); /* if the response size is good */ if (size == SNTP_MSG_LEN) { /* if this is a SNTP response... */ if (((sntpmsg.li_vn_mode & SNTP_MODE_MASK) == SNTP_MODE_SERVER) || ((sntpmsg.li_vn_mode & SNTP_MODE_MASK) == SNTP_MODE_BROADCAST)) { /* do time processing */ sntp_process(sntpmsg.receive_timestamp); } else { LWIP_DEBUGF( SNTP_DEBUG_WARN, ("sntp_request: not response frame code\n")); } } } else { LWIP_DEBUGF( SNTP_DEBUG_WARN, ("sntp_request: not sendto==%i\n", errno)); } } /* close the socket */ closesocket(sock); } } }
int main(int argc, char **argv) { struct netif netif; sigset_t mask, oldmask, empty; int ch; char ip_str[16] = {0}, nm_str[16] = {0}, gw_str[16] = {0}; /* startup defaults (may be overridden by one or more opts) */ IP4_ADDR(&gw, 192,168,0,1); IP4_ADDR(&ipaddr, 192,168,0,2); IP4_ADDR(&netmask, 255,255,255,0); trap_flag = 0; /* use debug flags defined by debug.h */ debug_flags = LWIP_DBG_OFF; while ((ch = getopt_long(argc, argv, "dhg:i:m:t:", longopts, NULL)) != -1) { switch (ch) { case 'd': debug_flags |= (LWIP_DBG_ON|LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_FRESH|LWIP_DBG_HALT); break; case 'h': usage(); exit(0); break; case 'g': ipaddr_aton(optarg, &gw); break; case 'i': ipaddr_aton(optarg, &ipaddr); break; case 'm': ipaddr_aton(optarg, &netmask); break; case 't': trap_flag = !0; /* @todo: remove this authentraps tweak when we have proper SET & non-volatile mem */ snmpauthentraps_set = 1; ipaddr_aton(optarg, &trap_addr); strncpy(ip_str, ipaddr_ntoa(&trap_addr),sizeof(ip_str)); printf("SNMP trap destination %s\n", ip_str); break; default: usage(); break; } } argc -= optind; argv += optind; strncpy(ip_str, ipaddr_ntoa(&ipaddr), sizeof(ip_str)); strncpy(nm_str, ipaddr_ntoa(&netmask), sizeof(nm_str)); strncpy(gw_str, ipaddr_ntoa(&gw), sizeof(gw_str)); printf("Host at %s mask %s gateway %s\n", ip_str, nm_str, gw_str); #ifdef PERF perf_init("/tmp/minimal.perf"); #endif /* PERF */ lwip_init(); printf("TCP/IP initialized.\n"); netif_add(&netif, &ipaddr, &netmask, &gw, NULL, mintapif_init, ethernet_input); netif_set_default(&netif); netif_set_up(&netif); #if SNMP_PRIVATE_MIB != 0 /* initialize our private example MIB */ lwip_privmib_init(); #endif snmp_trap_dst_ip_set(0,&trap_addr); snmp_trap_dst_enable(0,trap_flag); snmp_set_syscontact(syscontact_str,&syscontact_len); snmp_set_syslocation(syslocation_str,&syslocation_len); snmp_set_snmpenableauthentraps(&snmpauthentraps_set); snmp_init(); echo_init(); timer_init(); timer_set_interval(TIMER_EVT_ETHARPTMR, ARP_TMR_INTERVAL / 10); timer_set_interval(TIMER_EVT_TCPTMR, TCP_TMR_INTERVAL / 10); #if IP_REASSEMBLY timer_set_interval(TIMER_EVT_IPREASSTMR, IP_TMR_INTERVAL / 10); #endif printf("Applications started.\n"); while (1) { /* poll for input packet and ensure select() or read() arn't interrupted */ sigemptyset(&mask); sigaddset(&mask, SIGALRM); sigprocmask(SIG_BLOCK, &mask, &oldmask); /* start of critical section, poll netif, pass packet to lwIP */ if (mintapif_select(&netif) > 0) { /* work, immediatly end critical section hoping lwIP ended quickly ... */ sigprocmask(SIG_SETMASK, &oldmask, NULL); } else { /* no work, wait a little (10 msec) for SIGALRM */ sigemptyset(&empty); sigsuspend(&empty); /* ... end critical section */ sigprocmask(SIG_SETMASK, &oldmask, NULL); } if(timer_testclr_evt(TIMER_EVT_TCPTMR)) { tcp_tmr(); } #if IP_REASSEMBLY if(timer_testclr_evt(TIMER_EVT_IPREASSTMR)) { ip_reass_tmr(); } #endif if(timer_testclr_evt(TIMER_EVT_ETHARPTMR)) { etharp_tmr(); } } return 0; }
void ntp_setup(void) { tv_t tv; tz_t tz; time_t sec; struct ip_info getinfo; // Wait until we have an IP address before we set the time if(!network_init) return; if(ntp_init == 0) { ip_addr_t *addr = (ip_addr_t *)safecalloc(sizeof(ip_addr_t),1); // form pool.ntp.org ipaddr_aton("206.108.0.131", addr); sntp_setserver(1,addr); ipaddr_aton("167.114.204.238", addr); sntp_setserver(2,addr); #if 0 // Alternate time setting if the local router does NTP if(wifi_get_ip_info(0, &getinfo)) { printf("NTP:0 GW: %s\n", ipv4_2str(getinfo.gw.addr)); printf("NTP:0 IP: %s\n", ipv4_2str(getinfo.ip.addr)); sntp_setserver(1, & getinfo.gw); sntp_setserver(2, & getinfo.ip); } else { printf("NTP:0 failed to get GW address\n"); return; } #endif if( sntp_set_timezone(0) ) { printf("NTP: set_timeone OK\n"); sntp_init(); safefree(addr); ntp_init = 1; printf("NTP:1\n"); } else { printf("NTP: set_timeone Failed\n"); } } if(ntp_init == 1) { // they hard coded it to +8 hours from GMT if( (sec = sntp_get_current_timestamp()) > 10 ) { sntp_stop(); ntp_init = 2; } } if(ntp_init == 2) { time_t s; tm_t *p; printf("NTP:2\n"); // they return GMT + 8 // sec = sec - (8UL * 3600UL); tv.tv_sec = sec; printf("ntp_init: %s\n", asctime(gmtime(&sec))); printf("ntp_init: %s\n", ctime_gm(&sec)); tv.tv_usec = 0; tz.tz_minuteswest = 300; tz.tz_dsttime = 0; settimeofday(&tv, &tz); printf("SEC:%ld\n",sec); printf("TIME:%s\n", ctime(&sec)); printf("Zone: %d\n", (int) sntp_get_timezone()); ntp_init = 3; set_dst(tv.tv_sec); print_dst_gmt(); print_dst(); p = gmtime(&tv.tv_sec); mktime(p); printf("Localtime: %s\n", asctime(p)); } }
END_TEST START_TEST(test_ip6_aton_ipv4mapped) { int ret; ip_addr_t addr; ip6_addr_t addr6; const ip_addr_t addr_expected = IPADDR6_INIT_HOST(0, 0, 0xFFFF, 0xD4CC65D2); const char *full_ipv6_addr = "0:0:0:0:0:FFFF:D4CC:65D2"; const char *shortened_ipv6_addr = "::FFFF:D4CC:65D2"; const char *full_ipv4_mapped_addr = "0:0:0:0:0:FFFF:212.204.101.210"; const char *shortened_ipv4_mapped_addr = "::FFFF:212.204.101.210"; const char *bogus_ipv4_mapped_addr = "::FFFF:212.204.101.2101"; LWIP_UNUSED_ARG(_i); /* check IPv6 representation */ memset(&addr6, 0, sizeof(addr6)); ret = ip6addr_aton(full_ipv6_addr, &addr6); fail_unless(ret == 1); fail_unless(memcmp(&addr6, &addr_expected, 16) == 0); memset(&addr, 0, sizeof(addr)); ret = ipaddr_aton(full_ipv6_addr, &addr); fail_unless(ret == 1); fail_unless(memcmp(&addr, &addr_expected, 16) == 0); /* check shortened IPv6 representation */ memset(&addr6, 0, sizeof(addr6)); ret = ip6addr_aton(shortened_ipv6_addr, &addr6); fail_unless(ret == 1); fail_unless(memcmp(&addr6, &addr_expected, 16) == 0); memset(&addr, 0, sizeof(addr)); ret = ipaddr_aton(shortened_ipv6_addr, &addr); fail_unless(ret == 1); fail_unless(memcmp(&addr, &addr_expected, 16) == 0); /* checked shortened mixed representation */ memset(&addr6, 0, sizeof(addr6)); ret = ip6addr_aton(shortened_ipv4_mapped_addr, &addr6); fail_unless(ret == 1); fail_unless(memcmp(&addr6, &addr_expected, 16) == 0); memset(&addr, 0, sizeof(addr)); ret = ipaddr_aton(shortened_ipv4_mapped_addr, &addr); fail_unless(ret == 1); fail_unless(memcmp(&addr, &addr_expected, 16) == 0); /* checked mixed representation */ memset(&addr6, 0, sizeof(addr6)); ret = ip6addr_aton(full_ipv4_mapped_addr, &addr6); fail_unless(ret == 1); fail_unless(memcmp(&addr6, &addr_expected, 16) == 0); memset(&addr, 0, sizeof(addr)); ret = ipaddr_aton(full_ipv4_mapped_addr, &addr); fail_unless(ret == 1); fail_unless(memcmp(&addr, &addr_expected, 16) == 0); /* checked bogus mixed representation */ memset(&addr6, 0, sizeof(addr6)); ret = ip6addr_aton(bogus_ipv4_mapped_addr, &addr6); fail_unless(ret == 0); memset(&addr, 0, sizeof(addr)); ret = ipaddr_aton(bogus_ipv4_mapped_addr, &addr); fail_unless(ret == 0); }
// Lua: client:send(data, function(c)), socket:send(port, ip, data, function(s)) int net_send( lua_State *L ) { lnet_userdata *ud = net_get_udata(L); if (!ud || ud->type == TYPE_TCP_SERVER) return luaL_error(L, "invalid user data"); ip_addr_t addr; uint16_t port; const char *data; size_t datalen = 0; int stack = 2; if (ud->type == TYPE_UDP_SOCKET) { size_t dl = 0; port = luaL_checkinteger(L, stack++); if (port == 0) return luaL_error(L, "need port"); const char *domain = luaL_checklstring(L, stack++, &dl); if (!domain) return luaL_error(L, "need IP address"); if (!ipaddr_aton(domain, &addr)) return luaL_error(L, "invalid IP address"); } data = luaL_checklstring(L, stack++, &datalen); if (!data || datalen == 0) return luaL_error(L, "no data to send"); if (lua_isfunction(L, stack) || lua_islightfunction(L, stack)) { lua_pushvalue(L, stack++); luaL_unref(L, LUA_REGISTRYINDEX, ud->client.cb_sent_ref); ud->client.cb_sent_ref = luaL_ref(L, LUA_REGISTRYINDEX); } if (ud->type == TYPE_UDP_SOCKET && !ud->pcb) { ud->udp_pcb = udp_new(); if (!ud->udp_pcb) return luaL_error(L, "cannot allocate PCB"); udp_recv(ud->udp_pcb, net_udp_recv_cb, ud); ip_addr_t laddr = {0}; err_t err = udp_bind(ud->udp_pcb, &laddr, 0); if (err != ERR_OK) { udp_remove(ud->udp_pcb); ud->udp_pcb = NULL; return lwip_lua_checkerr(L, err); } if (ud->self_ref == LUA_NOREF) { lua_pushvalue(L, 1); ud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX); } } if (!ud->pcb || ud->self_ref == LUA_NOREF) return luaL_error(L, "not connected"); err_t err; if (ud->type == TYPE_UDP_SOCKET) { struct pbuf *pb = pbuf_alloc(PBUF_TRANSPORT, datalen, PBUF_RAM); if (!pb) return luaL_error(L, "cannot allocate message buffer"); pbuf_take(pb, data, datalen); err = udp_sendto(ud->udp_pcb, pb, &addr, port); pbuf_free(pb); if (ud->client.cb_sent_ref != LUA_NOREF) { lua_rawgeti(L, LUA_REGISTRYINDEX, ud->client.cb_sent_ref); lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref); lua_call(L, 1, 0); } } else if (ud->type == TYPE_TCP_CLIENT) { err = tcp_write(ud->tcp_pcb, data, datalen, TCP_WRITE_FLAG_COPY); } return lwip_lua_checkerr(L, err); }
/** * Translates the name of a service location (for example, a host name) and/or * a service name and returns a set of socket addresses and associated * information to be used in creating a socket with which to address the * specified service. * Memory for the result is allocated internally and must be freed by calling * lwip_freeaddrinfo()! * * Due to a limitation in dns_gethostbyname, only the first address of a * host is returned. * Also, service names are not supported (only port numbers)! * * @param nodename descriptive name or address string of the host * (may be NULL -> local address) * @param servname port number as string of NULL * @param hints structure containing input values that set socktype and protocol * @param res pointer to a pointer where to store the result (set to NULL on failure) * @return 0 on success, non-zero on failure * * @todo: implement AI_V4MAPPED, AI_ADDRCONFIG */ int lwip_getaddrinfo(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { err_t err; ip_addr_t addr; struct addrinfo *ai; struct sockaddr_storage *sa = NULL; int port_nr = 0; size_t total_size; size_t namelen = 0; int ai_family; if (res == NULL) { return EAI_FAIL; } *res = NULL; if ((nodename == NULL) && (servname == NULL)) { return EAI_NONAME; } if (hints != NULL) { ai_family = hints->ai_family; if ((ai_family != AF_UNSPEC) #if LWIP_IPV4 && (ai_family != AF_INET) #endif /* LWIP_IPV4 */ #if LWIP_IPV6 && (ai_family != AF_INET6) #endif /* LWIP_IPV6 */ ) { return EAI_FAMILY; } } else { ai_family = AF_UNSPEC; } if (servname != NULL) { /* service name specified: convert to port number * @todo?: currently, only ASCII integers (port numbers) are supported (AI_NUMERICSERV)! */ port_nr = atoi(servname); if ((port_nr <= 0) || (port_nr > 0xffff)) { return EAI_SERVICE; } } if (nodename != NULL) { /* service location specified, try to resolve */ if ((hints != NULL) && (hints->ai_flags & AI_NUMERICHOST)) { /* no DNS lookup, just parse for an address string */ if (!ipaddr_aton(nodename, &addr)) { return EAI_NONAME; } #if LWIP_IPV4 && LWIP_IPV6 if ((IP_IS_V6_VAL(addr) && ai_family == AF_INET) || (IP_IS_V4_VAL(addr) && ai_family == AF_INET6)) { return EAI_NONAME; } #endif /* LWIP_IPV4 && LWIP_IPV6 */ } else { #if LWIP_IPV4 && LWIP_IPV6 /* AF_UNSPEC: prefer IPv4 */ u8_t type = NETCONN_DNS_IPV4_IPV6; if (ai_family == AF_INET) { type = NETCONN_DNS_IPV4; } else if (ai_family == AF_INET6) { type = NETCONN_DNS_IPV6; } #endif /* LWIP_IPV4 && LWIP_IPV6 */ err = netconn_gethostbyname_addrtype(nodename, &addr, type); if (err != ERR_OK) { return EAI_FAIL; } } } else { /* service location specified, use loopback address */ if ((hints != NULL) && (hints->ai_flags & AI_PASSIVE)) { ip_addr_set_any(ai_family == AF_INET6, &addr); } else { ip_addr_set_loopback(ai_family == AF_INET6, &addr); } } total_size = sizeof(struct addrinfo) + sizeof(struct sockaddr_storage); if (nodename != NULL) { namelen = strlen(nodename); if (namelen > DNS_MAX_NAME_LENGTH) { /* invalid name length */ return EAI_FAIL; } LWIP_ASSERT("namelen is too long", total_size + namelen + 1 > total_size); total_size += namelen + 1; } /* If this fails, please report to lwip-devel! :-) */ LWIP_ASSERT("total_size <= NETDB_ELEM_SIZE: please report this!", total_size <= NETDB_ELEM_SIZE); ai = (struct addrinfo *)memp_malloc(MEMP_NETDB); if (ai == NULL) { return EAI_MEMORY; } memset(ai, 0, total_size); /* cast through void* to get rid of alignment warnings */ sa = (struct sockaddr_storage *)(void*)((u8_t*)ai + sizeof(struct addrinfo)); if (IP_IS_V6_VAL(addr)) { #if LWIP_IPV6 struct sockaddr_in6 *sa6 = (struct sockaddr_in6*)sa; /* set up sockaddr */ inet6_addr_from_ip6addr(&sa6->sin6_addr, ip_2_ip6(&addr)); sa6->sin6_family = AF_INET6; sa6->sin6_len = sizeof(struct sockaddr_in6); sa6->sin6_port = lwip_htons((u16_t)port_nr); ai->ai_family = AF_INET6; #endif /* LWIP_IPV6 */ } else { #if LWIP_IPV4 struct sockaddr_in *sa4 = (struct sockaddr_in*)sa; /* set up sockaddr */ inet4_addr_from_ip4addr(&sa4->sin_addr, ip_2_ip4(&addr)); sa4->sin_family = AF_INET; sa4->sin_len = sizeof(struct sockaddr_in); sa4->sin_port = lwip_htons((u16_t)port_nr); ai->ai_family = AF_INET; #endif /* LWIP_IPV4 */ } /* set up addrinfo */ if (hints != NULL) { /* copy socktype & protocol from hints if specified */ ai->ai_socktype = hints->ai_socktype; ai->ai_protocol = hints->ai_protocol; } if (nodename != NULL) { /* copy nodename to canonname if specified */ ai->ai_canonname = ((char*)ai + sizeof(struct addrinfo) + sizeof(struct sockaddr_storage)); MEMCPY(ai->ai_canonname, nodename, namelen); ai->ai_canonname[namelen] = 0; } ai->ai_addrlen = sizeof(struct sockaddr_storage); ai->ai_addr = (struct sockaddr*)sa; *res = ai; return 0; }
// Lua: server:listen(port, addr, function(c)), socket:listen(port, addr) int net_listen( lua_State *L ) { lnet_userdata *ud = net_get_udata(L); if (!ud || ud->type == TYPE_TCP_CLIENT) return luaL_error(L, "invalid user data"); if (ud->pcb) return luaL_error(L, "already listening"); int stack = 2; uint16_t port = 0; const char *domain = "0.0.0.0"; if (lua_isnumber(L, stack)) port = lua_tointeger(L, stack++); if (lua_isstring(L, stack)) { size_t dl = 0; domain = luaL_checklstring(L, stack++, &dl); } ip_addr_t addr; if (!ipaddr_aton(domain, &addr)) return luaL_error(L, "invalid IP address"); if (ud->type == TYPE_TCP_SERVER) { if (lua_isfunction(L, stack) || lua_islightfunction(L, stack)) { lua_pushvalue(L, stack++); luaL_unref(L, LUA_REGISTRYINDEX, ud->server.cb_accept_ref); ud->server.cb_accept_ref = luaL_ref(L, LUA_REGISTRYINDEX); } else { return luaL_error(L, "need callback"); } } err_t err = ERR_OK; switch (ud->type) { case TYPE_TCP_SERVER: ud->tcp_pcb = tcp_new(); if (!ud->tcp_pcb) return luaL_error(L, "cannot allocate PCB"); ud->tcp_pcb->so_options |= SOF_REUSEADDR; err = tcp_bind(ud->tcp_pcb, &addr, port); if (err == ERR_OK) { tcp_arg(ud->tcp_pcb, ud); struct tcp_pcb *pcb = tcp_listen(ud->tcp_pcb); if (!pcb) { err = ERR_MEM; } else { ud->tcp_pcb = pcb; tcp_accept(ud->tcp_pcb, net_accept_cb); } } break; case TYPE_UDP_SOCKET: ud->udp_pcb = udp_new(); if (!ud->udp_pcb) return luaL_error(L, "cannot allocate PCB"); udp_recv(ud->udp_pcb, net_udp_recv_cb, ud); err = udp_bind(ud->udp_pcb, &addr, port); break; } if (err != ERR_OK) { switch (ud->type) { case TYPE_TCP_SERVER: tcp_close(ud->tcp_pcb); ud->tcp_pcb = NULL; break; case TYPE_UDP_SOCKET: udp_remove(ud->udp_pcb); ud->udp_pcb = NULL; break; } return lwip_lua_checkerr(L, err); } if (ud->self_ref == LUA_NOREF) { lua_pushvalue(L, 1); ud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX); } return 0; }