如果要访问广域网中的服务器,则必须先通过DNS解析域名,然后再传入tcp_connect中。 例如: void find_server_ip(struct netif *netif) { struct ip4_addr dnsip; err_t err = dns_gethostbyname("zh.arslanbar.net", &dnsip, dnsfound, NULL); if (err == ERR_OK) test(&dnsip); }
void dnsfound(const char *name, const ip_addr_t *ipaddr, void *callback_arg) { test(ipaddr); }
void test(const ip_addr_t *ipaddr) { struct tcp_pcb *tpcb = tcp_new(); tcp_err(tpcb, http_err); tcp_connect(tpcb, ipaddr, 80, http_connected); // HTTP端口号为80 }
void http_err(void *arg, err_t err) { printf("Connection failed! err=%d\n", err); }
err_t http_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { const char *str = "GET /API/ HTTP/1.1\r\nHost: zh.arslanbar.net\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\n\r\n"; tcp_write(tpcb, str, strlen(str), 0); tcp_recv(tpcb, http_recv); return ERR_OK; }
err_t http_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) { uint16_t i; char *pstr; if (p != NULL) // 这个条件很重要, 因为http_recv可能会不止调用一次 { pstr = (char *)p->payload; for (i = 0; i < p->len; i++) putchar(pstr[i]); putchar('\n'); tcp_recved(tpcb, p->tot_len); pbuf_free(p); } tcp_close(tpcb); return ERR_OK; }
|