66#include <sys/socket.h>
77#include <netdb.h>
88
9- void ffNetworkingGetHttp (const char * host , const char * path , uint32_t timeout , FFstrbuf * buffer )
9+ int ffNetworkingSendHttpRequest (const char * host , const char * path , uint32_t timeout )
1010{
11- struct addrinfo hints = {0 };
12- hints .ai_family = AF_INET ;
13- hints .ai_socktype = SOCK_STREAM ;
11+ struct addrinfo hints = {
12+ .ai_family = AF_INET ,
13+ .ai_socktype = SOCK_STREAM ,
14+ };
1415
1516 struct addrinfo * addr ;
1617
1718 if (getaddrinfo (host , "80" , & hints , & addr ) != 0 )
18- return ;
19+ return -1 ;
1920
20- int sock = socket (addr -> ai_family , addr -> ai_socktype , addr -> ai_protocol );
21- if (sock == -1 )
21+ int sockfd = socket (addr -> ai_family , addr -> ai_socktype , addr -> ai_protocol );
22+ if (sockfd == -1 )
2223 {
2324 freeaddrinfo (addr );
24- return ;
25+ return -1 ;
2526 }
2627
2728 if (timeout > 0 )
2829 {
2930 struct timeval timev ;
3031 timev .tv_sec = 0 ;
3132 timev .tv_usec = (__typeof__ (timev .tv_usec )) (timeout * 1000 ); //milliseconds to microseconds
32- setsockopt (sock , SOL_SOCKET , SO_RCVTIMEO , & timev , sizeof (timev ));
33+ setsockopt (sockfd , SOL_SOCKET , SO_RCVTIMEO , & timev , sizeof (timev ));
3334 }
3435
35- if (connect (sock , addr -> ai_addr , addr -> ai_addrlen ) == -1 )
36+ if (connect (sockfd , addr -> ai_addr , addr -> ai_addrlen ) == -1 )
3637 {
37- close (sock );
38+ close (sockfd );
3839 freeaddrinfo (addr );
39- return ;
40+ return -1 ;
4041 }
4142
4243 freeaddrinfo (addr );
@@ -49,21 +50,32 @@ void ffNetworkingGetHttp(const char* host, const char* path, uint32_t timeout, F
4950 ffStrbufAppendS (& command , host );
5051 ffStrbufAppendS (& command , "\r\n\r\n" );
5152
52- if (send (sock , command .chars , command .length , 0 ) == -1 )
53+ if (send (sockfd , command .chars , command .length , 0 ) == -1 )
5354 {
5455 ffStrbufDestroy (& command );
55- close (sock );
56- return ;
56+ close (sockfd );
57+ return -1 ;
5758 }
59+ ffStrbufDestroy (& command );
60+ return sockfd ;
61+ }
5862
59- ssize_t received = recv (sock , buffer -> chars + buffer -> length , ffStrbufGetFree (buffer ), 0 );
63+ void ffNetworkingRecvHttpResponse (int sockfd , FFstrbuf * buffer )
64+ {
65+ ssize_t received = recv (sockfd , buffer -> chars + buffer -> length , ffStrbufGetFree (buffer ), 0 );
6066
6167 if (received > 0 )
6268 {
6369 buffer -> length += (uint32_t ) received ;
6470 buffer -> chars [buffer -> length ] = '\0' ;
6571 }
6672
67- ffStrbufDestroy (& command );
68- close (sock );
73+ close (sockfd );
74+ }
75+
76+ void ffNetworkingGetHttp (const char * host , const char * path , uint32_t timeout , FFstrbuf * buffer )
77+ {
78+ int sockfd = ffNetworkingSendHttpRequest (host , path , timeout );
79+ if (sockfd > 0 )
80+ ffNetworkingRecvHttpResponse (sockfd , buffer );
6981}
0 commit comments