#include "hw/hw_led.h" #include "tcp_socket.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include // vsnprintf #include // va_list /* Network interface global variables */ static struct ip_addr ipaddr, netmask, gw; static struct netif netif; static void init(void) { /* Enable all the interrupts */ IRQ_ENABLE; /* Initialize debugging module (allow kprintf(), etc.) */ kdbg_init(); /* Initialize system timer */ timer_init(); proc_init(); /* Initialize TCP/IP stack */ tcpip_init(NULL, NULL); /* Bring up the network interface */ netif_add(&netif, &ipaddr, &netmask, &gw, NULL, ethernetif_init, ip_input); netif_set_default(&netif); netif_set_up(&netif); } static char linebuf[200]; #define COMMAND_PORT 20000 static char readbuf[200]; static int protocol_run(int sockfd) { ssize_t rd = lwip_recv(sockfd, readbuf, sizeof(readbuf), 0); // if rd == 0, the other end has performed an orderly shutdown if (rd == 0) { kprintf("Peer closed the connection\n"); return -1; } // terminate the string and remove \n at end readbuf[rd - 1] = '\n'; int len = snprintf(linebuf, sizeof(linebuf), "%s\r\n", readbuf); lwip_send(sockfd, linebuf, len, 0); return 0; } int main(void) { init(); dhcp_start(&netif); while (!netif.ip_addr.addr) { dhcp_fine_tmr(); timer_delay(DHCP_FINE_TIMER_MSECS); } kprintf(">>> dhcp ok: ip = %s (kernel %s)\n", ip_ntoa(&netif.ip_addr.addr), CONFIG_KERN_PREEMPT ? "preempt" : "coop"); int server = -1; struct sockaddr_in addr; server = lwip_socket(AF_INET, SOCK_STREAM, 0); if (server < 0) kprintf("Error opening socket\n"); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(COMMAND_PORT); addr.sin_addr.s_addr = INADDR_ANY; if (lwip_bind(server, (struct sockaddr *)&addr, sizeof(addr)) == -1) kprintf("Error binding port %hd\n", COMMAND_PORT); if (lwip_listen(server, 1) == -1) kprintf("Error listen\n"); while (1) { bool done = false; int protocol_sock = lwip_accept(server, NULL, NULL); if (protocol_sock == -1) { kprintf("Error accepting connection\n"); continue; } kprintf("Accepted connection on socket %d\n", protocol_sock); while (!done) { if (protocol_run(protocol_sock)) { done = true; } } lwip_close(protocol_sock); kprintf("Closing socket %d\n", protocol_sock); } }