void Socket::connect(const char* server, int port) { my_addr.sin_port = htons(port); my_addr.sin_addr = *getHostByName(server); memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero)); int n = ::connect(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)); if(n == -1) error(n); }
const char* Socket::getHostName() { char name[256]; int n = gethostname(name, sizeof(name)); if(n == -1) throw(n); return inet_ntoa(*getHostByName(name)); }
error_t sntpClientTest(void) { error_t error; time_t unixTime; IpAddr ipAddr; NtpTimestamp timestamp; DateTime date; //Debug message TRACE_INFO("\r\n\r\nResolving server name...\r\n"); //Resolve SNTP server name error = getHostByName(NULL, "0.fr.pool.ntp.org", &ipAddr, 0); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to resolve server name!\r\n"); //Exit immediately return error; } //Debug message TRACE_INFO("Requesting time from SNTP server %s\r\n", ipAddrToString(&ipAddr, NULL)); //Retrieve current time from NTP server using SNTP protocol error = sntpClientGetTimestamp(NULL, &ipAddr, ×tamp); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to retrieve NTP timestamp!\r\n"); } else { //Unix time starts on January 1st, 1970 unixTime = timestamp.seconds - 2208988800; //Convert Unix timestamp to date convertUnixTimeToDate(unixTime, &date); //Debug message TRACE_INFO("Current date/time: %s\r\n", formatDate(&date, NULL)); //Move cursor lcdSetCursor(8, 0); //Refresh LCD display printf("%04u/%02u/%02u %02u:%02u:%02u", date.year, date.month, date.day, date.hours, date.minutes, date.seconds); } //Return status code return error; }
int WiFiDrv::getHostByName(const char *aHostname, IPAddress &aResult) { uint8_t retry = 10; if ( reqHostByName(aHostname) ) { while ( !getHostByName(aResult) && --retry > 0 ) { delay(1000); } } else { return 0; } return retry > 0; }
int_t gethostbyname(const char_t *name, hostent *info) { error_t error; IpAddr ipAddr; //Check input parameters if(!name || !info) return ERROR_INVALID_PARAMETER; //Resolve host address error = getHostByName(NULL, name, &ipAddr, 1, NULL, 0); //Address resolution failed? if(error) return error; #if (IPV4_SUPPORT == ENABLED) //IPv4 address? if(ipAddr.length == sizeof(Ipv4Addr)) { //Set address family info->h_addrtype = AF_INET; //Copy IPv4 address info->h_length = sizeof(Ipv4Addr); ipv4CopyAddr(info->h_addr, &ipAddr.ipv4Addr); } else #endif #if (IPV6_SUPPORT == ENABLED) //IPv6 address? if(ipAddr.length == sizeof(Ipv6Addr)) { //Set address family info->h_addrtype = AF_INET6; //Copy IPv6 address info->h_length = sizeof(Ipv6Addr); ipv6CopyAddr(info->h_addr, &ipAddr.ipv6Addr); } else #endif //Invalid address? { //Report an error return ERROR_FAILURE; } //Successful processing return NO_ERROR; }
PRStatus initAddr (PRNetAddr* addr, const char* host, int port = -1) { std::string sHost = host; if (PR_StringToNetAddr(sHost.c_str(), addr) == PR_FAILURE) { std::string sIp; std::string sPort; if (sHost[0] == '[') { sIp = sHost.substr(1, sHost.find_last_of("]")-1); sPort = sHost.substr(sHost.find_last_of("]")+2); } else { sIp = sHost.substr(0, sHost.find_last_of(":")); sPort = sHost.substr(sHost.find_last_of(":")+1); } if (!sPort.empty()) { int tmp = atoi(sPort.c_str()); if (tmp >= 1 && tmp <= 65536) { port = tmp; } } if (PR_StringToNetAddr(sIp.c_str(), addr) == PR_FAILURE) { char* ip = getHostByName(sIp.c_str()); if (ip == NULL) { return PR_FAILURE; } sIp = ip; delete [] ip; if (PR_StringToNetAddr(sIp.c_str(), addr) == PR_FAILURE) { return PR_FAILURE; } } } if (port >= 1 && port <= 65536) { PR_InitializeNetAddr(PR_IpAddrNull, port, addr); } return PR_SUCCESS; }
Status SocketHelper::createSocket(char *host, int port) { snprintf(logMsg, BUFFER_SIZE, "%s", __func__); callJavaMethod(); if (strlen(host) >= sizeof(socketHost)) { LOGE("%s: socket host is too long !", __func__); return ERROR; } strncpy(socketHost, host, strlen(host)); if (isConvert) { if (getHostByName(host) == ERROR) { return ERROR; } } else { strncpy(socketIP, host, strlen(host)); } LOGI("%s: socketHost = %s", __func__, socketHost); socketfd = socket(AF_INET, SOCK_STREAM, 0); if (socketfd < 0) { LOGE("%s: socket create fail !", __func__); return ERROR; } LOGI("%s: socketfd = %d", __func__, socketfd); socket_addr.addr4.sin_family = AF_INET; // AF_INET6 for IPV6 socket_addr.addr4.sin_port = htons(port); // ntohs(network to host short) // socket_addr.addr4.sin_addr.s_addr = inet_addr(socketIP); // in_addr_t // inet_aton(socketIP, &socket_addr.addr4.sin_addr); inet_pton(AF_INET, socketIP, &socket_addr.addr4.sin_addr); // LOGI("%s: ip = %s, port = %d", __func__, inet_ntoa(socket_addr.addr4.sin_addr), port); char buffer[64]; inet_ntop(AF_INET, &socket_addr.addr4.sin_addr, buffer, sizeof(buffer)); LOGI("%s: socketIP = %s, socketPort = %d", __func__, buffer, port); return OK; }
error_t ftpClientTest(void) { error_t error; size_t length; IpAddr ipAddr; FtpClientContext ftpContext; static char_t buffer[256]; //Debug message TRACE_INFO("\r\n\r\nResolving server name...\r\n"); //Resolve FTP server name error = getHostByName(NULL, "ftp.gnu.org", &ipAddr, 0); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to resolve server name!\r\n"); //Exit immediately return error; } //Debug message TRACE_INFO("Connecting to FTP server %s\r\n", ipAddrToString(&ipAddr, NULL)); //Connect to the FTP server error = ftpConnect(&ftpContext, NULL, &ipAddr, 21, FTP_NO_SECURITY | FTP_PASSIVE_MODE); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to connect to FTP server!\r\n"); //Exit immediately return error; } //Debug message TRACE_INFO("Successful connection\r\n"); //Start of exception handling block do { //Login to the FTP server using the provided username and password error = ftpLogin(&ftpContext, "anonymous", "password", ""); //Any error to report? if(error) break; //Open the specified file for reading error = ftpOpenFile(&ftpContext, "welcome.msg", FTP_FOR_READING | FTP_BINARY_TYPE); //Any error to report? if(error) break; //Dump the contents of the file while(1) { //Read data error = ftpReadFile(&ftpContext, buffer, sizeof(buffer) - 1, &length, 0); //End of file? if(error) break; //Properly terminate the string with a NULL character buffer[length] = '\0'; //Dump current data TRACE_INFO("%s", buffer); } //End the string with a line feed TRACE_INFO("\r\n"); //Close the file error = ftpCloseFile(&ftpContext); //End of exception handling block } while(0); //Close the connection ftpClose(&ftpContext); //Debug message TRACE_INFO("Connection closed...\r\n"); //Return status code return error; }
error_t sslClientTest(void) { error_t error; size_t length; IpAddr ipAddr; static char_t buffer[256]; //Underlying socket Socket *socket = NULL; //SSL/TLS context TlsContext *tlsContext = NULL; //Debug message TRACE_INFO("Resolving server name...\r\n"); //Resolve SSL server name error = getHostByName(NULL, APP_SERVER_NAME, &ipAddr, 0); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to resolve server name!\r\n"); //Exit immediately return error; } //Create a new socket to handle the request socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP); //Any error to report? if(!socket) { //Debug message TRACE_INFO("Failed to open socket!\r\n"); //Exit immediately return ERROR_OPEN_FAILED; } //Start of exception handling block do { //Debug message TRACE_INFO("Connecting to SSL server %s\r\n", ipAddrToString(&ipAddr, NULL)); //Connect to the SSL server error = socketConnect(socket, &ipAddr, APP_SERVER_PORT); //Any error to report? if(error) break; //Initialize SSL/TLS context tlsContext = tlsInit(); //Initialization failed? if(!tlsContext) { //Report an error error = ERROR_OUT_OF_MEMORY; //Exit immediately break; } //Bind TLS to the relevant socket error = tlsSetSocket(tlsContext, socket); //Any error to report? if(error) break; //Select client operation mode error = tlsSetConnectionEnd(tlsContext, TLS_CONNECTION_END_CLIENT); //Any error to report? if(error) break; //Set the PRNG algorithm to be used error = tlsSetPrng(tlsContext, YARROW_PRNG_ALGO, &yarrowContext); //Any error to report? if(error) break; #if (APP_SET_CIPHER_SUITES == ENABLED) //Preferred cipher suite list error = tlsSetCipherSuites(tlsContext, cipherSuites, arraysize(cipherSuites)); //Any error to report? if(error) break; #endif #if (APP_SET_SERVER_NAME == ENABLED) //Set the fully qualified domain name of the server error = tlsSetServerName(tlsContext, APP_SERVER_NAME); //Any error to report? if(error) break; #endif #if (APP_SET_TRUSTED_CA_LIST == ENABLED) //Import the list of trusted CA certificates error = tlsSetTrustedCaList(tlsContext, trustedCaList, trustedCaListLength); //Any error to report? if(error) break; #endif #if (APP_SET_CLIENT_CERT == ENABLED) //Import the client's certificate error = tlsAddCertificate(tlsContext, clientCert, clientCertLength, clientPrivateKey, clientPrivateKeyLength); //Any error to report? if(error) break; #endif //Establish a secure session error = tlsConnect(tlsContext); //TLS handshake failure? if(error) break; //Format HTTP request sprintf(buffer, "GET %s HTTP/1.0\r\nHost: %s:%u\r\n\r\n", APP_REQUEST_URI, APP_SERVER_NAME, APP_SERVER_PORT); //Debug message TRACE_INFO("\r\n"); TRACE_INFO("HTTP request:\r\n%s", buffer); //Send the request error = tlsWrite(tlsContext, buffer, strlen(buffer), 0); //Any error to report? if(error) break; //Debug message TRACE_INFO("HTTP response:\r\n"); //Read the whole response while(1) { //Read data error = tlsRead(tlsContext, buffer, sizeof(buffer) - 1, &length, 0); //End of stream? if(error) break; //Properly terminate the string with a NULL character buffer[length] = '\0'; //Debug message TRACE_INFO("%s", buffer); } //Successfull processing error = NO_ERROR; //End of exception handling block } while(0); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to communicate with SSL server!\r\n"); } //Terminate TLS session tlsFree(tlsContext); //Close socket socketClose(socket); //Debug message TRACE_INFO("Connection closed...\r\n"); //Return status code return error; }
error_t smtpSendMail(const SmtpAuthInfo *authInfo, const SmtpMail *mail) { error_t error; uint_t i; uint_t replyCode; IpAddr serverIpAddr; SmtpClientContext *context; //Check parameters if(!authInfo || !mail) return ERROR_INVALID_PARAMETER; //Make sure the server name is valid if(!authInfo->serverName) return ERROR_INVALID_PARAMETER; //Debug message TRACE_INFO("Sending a mail to %s port %" PRIu16 "...\r\n", authInfo->serverName, authInfo->serverPort); //The specified SMTP server can be either an IP or a host name error = getHostByName(authInfo->interface, authInfo->serverName, &serverIpAddr, 0); //Unable to resolve server name? if(error) return ERROR_NAME_RESOLUTION_FAILED; //Allocate a memory buffer to hold the SMTP client context context = osAllocMem(sizeof(SmtpClientContext)); //Failed to allocate memory? if(!context) return ERROR_OUT_OF_MEMORY; //Open a TCP socket context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP); //Failed to open socket? if(!context->socket) { //Free previously allocated resources osFreeMem(context); //Report an error return ERROR_OPEN_FAILED; } #if (SMTP_TLS_SUPPORT == ENABLED) //Do not use SSL/TLS for the moment context->tlsContext = NULL; #endif //Start of exception handling block do { //Bind the socket to a particular network interface? if(authInfo->interface) { //Associate the socket with the relevant interface error = socketBindToInterface(context->socket, authInfo->interface); //Any error to report? if(error) break; } //Set timeout for blocking operations error = socketSetTimeout(context->socket, SMTP_DEFAULT_TIMEOUT); //Any error to report? if(error) break; //Connect to the SMTP server error = socketConnect(context->socket, &serverIpAddr, authInfo->serverPort); //Connection to server failed? if(error) break; #if (SMTP_TLS_SUPPORT == ENABLED) //Open a secure SSL/TLS session? if(authInfo->useTls) { //Initialize TLS context context->tlsContext = tlsInit(); //Initialization failed? if(!context->tlsContext) { //Unable to allocate memory error = ERROR_OUT_OF_MEMORY; //Stop immediately break; } //Bind TLS to the relevant socket error = tlsSetSocket(context->tlsContext, context->socket); //Any error to report? if(error) break; //Select client operation mode error = tlsSetConnectionEnd(context->tlsContext, TLS_CONNECTION_END_CLIENT); //Any error to report? if(error) break; //Set the PRNG algorithm to be used error = tlsSetPrng(context->tlsContext, authInfo->prngAlgo, authInfo->prngContext); //Any error to report? if(error) break; //Perform TLS handshake error = tlsConnect(context->tlsContext); //Failed to established a TLS session? if(error) break; } #endif //Wait for the connection greeting reply error = smtpSendCommand(context, NULL, &replyCode, NULL); //Any communication error to report? if(error) break; //Check whether the greeting message was properly received if(!SMTP_REPLY_CODE_2YZ(replyCode)) { //An unexpected response was received... error = ERROR_UNEXPECTED_RESPONSE; //Stop immediately break; } //Clear security features context->authLoginSupported = FALSE; context->authPlainSupported = FALSE; context->authCramMd5Supported = FALSE; context->startTlsSupported = FALSE; //Send EHLO command and parse server response error = smtpSendCommand(context, "EHLO [127.0.0.1]\r\n", &replyCode, smtpEhloReplyCallback); //Any communication error to report? if(error) break; //Check SMTP response code if(!SMTP_REPLY_CODE_2YZ(replyCode)) { //An unexpected response was received... error = ERROR_UNEXPECTED_RESPONSE; //Stop immediately break; } #if (SMTP_TLS_SUPPORT == ENABLED) //Check whether the STARTTLS command is supported if(context->startTlsSupported && !context->tlsContext) { //Send STARTTLS command error = smtpSendCommand(context, "STARTTLS\r\n", &replyCode, NULL); //Any communication error to report? if(error) break; //Check SMTP response code if(!SMTP_REPLY_CODE_2YZ(replyCode)) { //An unexpected response was received... error = ERROR_UNEXPECTED_RESPONSE; //Stop immediately break; } //Initialize TLS context context->tlsContext = tlsInit(); //Initialization failed? if(!context->tlsContext) { //Unable to allocate memory error = ERROR_OUT_OF_MEMORY; //Stop immediately break; } //Bind TLS to the relevant socket error = tlsSetSocket(context->tlsContext, context->socket); //Any error to report? if(error) break; //Select client operation mode error = tlsSetConnectionEnd(context->tlsContext, TLS_CONNECTION_END_CLIENT); //Any error to report? if(error) break; //Set the PRNG algorithm to be used error = tlsSetPrng(context->tlsContext, authInfo->prngAlgo, authInfo->prngContext); //Any error to report? if(error) break; //Perform TLS handshake error = tlsConnect(context->tlsContext); //Failed to established a TLS session? if(error) break; //Clear security features context->authLoginSupported = FALSE; context->authPlainSupported = FALSE; context->authCramMd5Supported = FALSE; //Send EHLO command and parse server response error = smtpSendCommand(context, "EHLO [127.0.0.1]\r\n", &replyCode, smtpEhloReplyCallback); //Any communication error to report? if(error) break; //Check SMTP response code if(!SMTP_REPLY_CODE_2YZ(replyCode)) { //An unexpected response was received... error = ERROR_UNEXPECTED_RESPONSE; //Stop immediately break; } } #endif //Authentication requires a valid user name and password if(authInfo->userName && authInfo->password) { #if (SMTP_LOGIN_AUTH_SUPPORT == ENABLED) //LOGIN authentication mechanism supported? if(context->authLoginSupported) { //Perform LOGIN authentication error = smtpSendAuthLogin(context, authInfo); //Authentication failed? if(error) break; } else #endif #if (SMTP_PLAIN_AUTH_SUPPORT == ENABLED) //PLAIN authentication mechanism supported? if(context->authPlainSupported) { //Perform PLAIN authentication error = smtpSendAuthPlain(context, authInfo); //Authentication failed? if(error) break; } else #endif #if (SMTP_CRAM_MD5_AUTH_SUPPORT == ENABLED) //CRAM-MD5 authentication mechanism supported? if(context->authCramMd5Supported) { //Perform CRAM-MD5 authentication error = smtpSendAuthCramMd5(context, authInfo); //Authentication failed? if(error) break; } else #endif //No authentication mechanism supported? { //Skip authentication step } } //Format the MAIL FROM command (a null return path must be accepted) if(mail->from.addr) sprintf(context->buffer, "MAIL FROM:<%s>\r\n", mail->from.addr); else strcpy(context->buffer, "MAIL FROM:<>\r\n"); //Send the command to the server error = smtpSendCommand(context, context->buffer, &replyCode, NULL); //Any communication error to report? if(error) break; //Check SMTP response code if(!SMTP_REPLY_CODE_2YZ(replyCode)) { //An unexpected response was received... error = ERROR_UNEXPECTED_RESPONSE; //Stop immediately break; } //Format the RCPT TO command for(i = 0; i < mail->recipientCount; i++) { //Skip recipient addresses that are not valid if(!mail->recipients[i].addr) continue; //Format the RCPT TO command sprintf(context->buffer, "RCPT TO:<%s>\r\n", mail->recipients[i].addr); //Send the command to the server error = smtpSendCommand(context, context->buffer, &replyCode, NULL); //Any communication error to report? if(error) break; //Check SMTP response code if(!SMTP_REPLY_CODE_2YZ(replyCode)) { //An unexpected response was received... error = ERROR_UNEXPECTED_RESPONSE; //Stop immediately break; } } //Propagate exception if necessary if(error) break; //Send message body error = smtpSendData(context, mail); //Any error to report? if(error) break; //End of exception handling block } while(0); //Check status code if(error == NO_ERROR || error == ERROR_UNEXPECTED_RESPONSE || error == ERROR_AUTHENTICATION_FAILED) { //Properly disconnect from the SMTP server smtpSendCommand(context, "QUIT\r\n", &replyCode, NULL); } #if (SMTP_TLS_SUPPORT == ENABLED) //Gracefully close SSL/TLS session if(context->tlsContext != NULL) tlsFree(context->tlsContext); #endif //Close socket socketClose(context->socket); //Clean up previously allocated resources osFreeMem(context); //Return status code return error; }
NetworkAddress * NetworkAddress_New(const char * uri, int uriLength) { NetworkAddress * result = NULL; if (uri && uriLength > 0) { if (!result) { bool secure = false; int index = 0; int startIndex = 0; int port = 5683; char hostname[MAX_URI_LENGTH]; int hostnameLength = 0; UriParseState state = UriParseState_Scheme; while (index < uriLength) { if (state == UriParseState_Scheme) { if ((uri[index] == ':') && ((index + 2) < uriLength) && (uri[index+1] == '/') && (uri[index+2] == '/')) { int length = index - startIndex; if ((length == 4) && (strncmp(&uri[startIndex],"coap", length) == 0)) { } else if ((length == 5) && (strncmp(&uri[startIndex],"coaps", length) == 0)) { port = 5684; secure = true; } else { break; } state = UriParseState_Hostname; index += 2; startIndex = index + 1; } index++; } else if (state == UriParseState_Hostname) { if ((uri[index] == '[') ) { index++; startIndex = index; while (index < uriLength) { if (uri[index] == ']') { break; } hostname[hostnameLength] = uri[index]; hostnameLength++; index++; } } else if ((uri[index] == ':') || (uri[index] == '/') ) { hostname[hostnameLength] = 0; if (uri[index] == '/') break; state = UriParseState_Port; port = 0; startIndex = index + 1; } else { hostname[hostnameLength] = uri[index]; hostnameLength++; } index++; } else if (state == UriParseState_Port) { if (uri[index] == '/') { break; } else if (isdigit(uri[index])) { port = (port * 10) + (uri[index] - '0'); } index++; } } if (state == UriParseState_Hostname) { hostname[hostnameLength] = 0; } if (hostnameLength > 0 && port > 0) { uip_ipaddr_t * resolvedAddress = getHostByName(hostname); if (resolvedAddress) { NetworkAddress * networkAddress = getCachedAddress(resolvedAddress, port); if(!networkAddress) { networkAddress = addCachedAddress(resolvedAddress, port, secure); } if (networkAddress) { result = networkAddress; } } } } if(result) { result->useCount++; } } return result; }
error_t icecastClientConnect(IcecastClientContext *context) { error_t error; size_t length; IpAddr serverIpAddr; //Icecast request template const char_t requestTemplate[] = "GET /%s HTTP/1.1\r\n" "Host: %s\r\n" "User-agent: UserAgent\r\n" "Icy-MetaData: 1\r\n" "Connection: close\r\n" "\r\n"; //The specified Icecast server can be either an IP or a host name error = getHostByName(context->settings.interface, context->settings.serverName, &serverIpAddr, 1, NULL, 0); //Unable to resolve server name? if(error) return error; //Open a TCP socket context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_PROTOCOL_TCP); //Failed to open socket? if(!context->socket) return ERROR_OUT_OF_RESOURCES; //Start of exception handling block do { //Adjust receive timeout error = socketSetTimeout(context->socket, ICECAST_CLIENT_TIMEOUT); //Any error to report? if(error) return error; //Connect to the specified Icecast server error = socketConnect(context->socket, &serverIpAddr, context->settings.serverPort); //Connection with server failed? if(error) return error; //Format Icecast request length = sprintf(context->buffer, requestTemplate, context->settings.resource, context->settings.serverName); //Debug message TRACE_DEBUG(context->buffer); //Send Icecast request error = socketSend(context->socket, context->buffer, length, NULL, SOCKET_FLAG_WAIT_ACK); //Failed to send the request? if(error) return error; //Parse response header while(1) { char_t *separator; char_t *property; char_t *value; //Read a line from the response header error = socketReceive(context->socket, context->buffer, ICECAST_CLIENT_METADATA_MAX_SIZE, &length, SOCKET_FLAG_BREAK_CRLF); //Failed to read data? if(error) break; //Properly terminate the string with a NULL character context->buffer[length] = '\0'; //The end of the header has been reached? if(!strcmp(context->buffer, "\r\n")) break; //Check whether a separator is present separator = strchr(context->buffer, ':'); //Separator found? if(separator) { //Split the line *separator = '\0'; //Get property name and value property = strTrimWhitespace(context->buffer); value = strTrimWhitespace(separator + 1); //Debug message TRACE_INFO("<%s>=<%s>\r\n", property, value); //Icy-Metaint property found? if(!strcasecmp(property, "Icy-Metaint")) context->blockSize = atoi(value); } } //End of exception handling block } while(0); //Check whether an error occurred if(error) { //Clean up side effects socketClose(context->socket); } //Return status code return error; }
error_t httpClientTest(void) { error_t error; size_t length; IpAddr ipAddr; Socket *socket; static char_t buffer[256]; //Debug message TRACE_INFO("\r\n\r\nResolving server name...\r\n"); //Resolve HTTP server name error = getHostByName(NULL, CLIENT_SERVER_NAME, &ipAddr, 1, NULL, 0); //Any error to report? if(error) { //Debug message TRACE_INFO("Failed to resolve server name!\r\n"); //Exit immedialtely return error; } //Create a new socket to handle the request socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_PROTOCOL_TCP); //Any error to report? if(!socket) { //Debug message TRACE_INFO("Failed to open socket!\r\n"); //Exit immedialtely return error; } //Start of exception handling block do { //Debug message TRACE_INFO("Connecting to HTTP server %s\r\n", ipAddrToString(&ipAddr, NULL)); //Connect to the HTTP server error = socketConnect(socket, &ipAddr, CLIENT_SERVER_PORT); //Any error to report? if(error) break; //Debug message TRACE_INFO("Successful connection\r\n"); //Format HTTP request length = sprintf(buffer, "GET %s HTTP/1.0\r\nHost: %s:%u\r\n\r\n", CLIENT_REQUEST_URI, CLIENT_SERVER_NAME, CLIENT_SERVER_PORT); //Debug message TRACE_INFO("\r\nHTTP request:\r\n%s", buffer); //Send HTTP request error = socketSend(socket, buffer, length, NULL, 0); //Any error to report? if(error) break; //Debug message TRACE_INFO("HTTP response header:\r\n"); //Parse HTTP response header while(1) { //Read the header line by line error = socketReceive(socket, buffer, sizeof(buffer) - 1, &length, SOCKET_FLAG_BREAK_CRLF); //End of stream? if(error) break; //Properly terminate the string with a NULL character buffer[length] = '\0'; //Dump current data TRACE_INFO("%s", buffer); //The end of the header has been reached? if(!strcmp(buffer, "\r\n")) break; } //Debug message TRACE_INFO("HTTP response body:\r\n"); //Parse HTTP response body while(1) { //Read response body error = socketReceive(socket, buffer, sizeof(buffer) - 1, &length, 0); //End of stream? if(error) break; //Properly terminate the string with a NULL character buffer[length] = '\0'; //Dump current data TRACE_INFO("%s", buffer); } //End of exception handling block } while(0); //Close the connection socketClose(socket); //Debug message TRACE_INFO("\r\nConnection closed...\r\n"); //Return status code return error; }