int lwip_getsockname (int s, struct sockaddr *name, socklen_t *namelen) { struct lwip_socket *sock; struct sockaddr_in sin; struct ip_addr *naddr; sock = get_socket(s); if (!sock) { set_errno(EBADF); return -1; } memset(&sin, 0, sizeof(sin)); sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; /* get the IP address and port of the remote host */ netconn_addr(sock->conn, &naddr, &sin.sin_port); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockname(%d, addr=", s)); ip_addr_debug_print(SOCKETS_DEBUG, naddr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%d)\n", sin.sin_port)); sin.sin_port = htons(sin.sin_port); sin.sin_addr.s_addr = naddr->addr; if (*namelen > sizeof(sin)) *namelen = sizeof(sin); memcpy(name, &sin, *namelen); sock_set_errno(sock, 0); return 0; }
static void dhcpserver_task(void *pxParameter) { /* netif_list isn't assigned until after user_init completes, which is why we do it inside the task */ state->server_if = netif_list; /* TODO: Make this configurable */ state->nc = netconn_new (NETCONN_UDP); if(!state->nc) { printf("DHCP Server Error: Failed to allocate socket.\r\n"); return; } netconn_bind(state->nc, IP_ADDR_ANY, DHCP_SERVER_PORT); while(1) { struct netbuf *netbuf; struct dhcp_msg received = { 0 }; /* Receive a DHCP packet */ err_t err = netconn_recv(state->nc, &netbuf); if(err != ERR_OK) { printf("DHCP Server Error: Failed to receive DHCP packet. err=%d\r\n", err); continue; } /* expire any leases that have passed */ uint32_t now = xTaskGetTickCount(); for(int i = 0; i < state->max_leases; i++) { uint32_t expires = state->leases[i].expires; if(expires && expires < now) state->leases[i].expires = 0; } ip_addr_t received_ip; u16_t port; netconn_addr(state->nc, &received_ip, &port); if(netbuf_len(netbuf) < offsetof(struct dhcp_msg, options)) { /* too short to be a valid DHCP client message */ netbuf_delete(netbuf); continue; } if(netbuf_len(netbuf) >= sizeof(struct dhcp_msg)) { printf("DHCP Server Warning: Client sent more options than we know how to parse. len=%d\r\n", netbuf_len(netbuf)); } netbuf_copy(netbuf, &received, sizeof(struct dhcp_msg)); netbuf_delete(netbuf); uint8_t *message_type = find_dhcp_option(&received, DHCP_OPTION_MESSAGE_TYPE, DHCP_OPTION_MESSAGE_TYPE_LEN, NULL); if(!message_type) { printf("DHCP Server Error: No message type field found"); continue; } printf("State dump. Message type %d\n", *message_type); for(int i = 0; i < state->max_leases; i++) { dhcp_lease_t *lease = &state->leases[i]; printf("lease slot %d expiry %d hwaddr %02x:%02x:%02x:%02x:%02x:%02x\r\n", i, lease->expires, lease->hwaddr[0], lease->hwaddr[1], lease->hwaddr[2], lease->hwaddr[3], lease->hwaddr[4], lease->hwaddr[5]); } switch(*message_type) { case DHCP_DISCOVER: handle_dhcp_discover(&received); break; case DHCP_REQUEST: handle_dhcp_request(&received); break; case DHCP_RELEASE: handle_dhcp_release(&received); default: printf("DHCP Server Error: Unsupported message type %d\r\n", *message_type); break; } } }