Graphics Programs Reference
In-Depth Information
bytes_to_send -= sent_bytes;
buffer += sent_bytes;
}
return 1; // Return 1 on success.
}
/* This function accepts a socket FD and a ptr to a destination
* buffer. It will receive from the socket until the EOL byte
* sequence in seen. The EOL bytes are read from the socket, but
* the destination buffer is terminated before these bytes.
* Returns the size of the read line (without EOL bytes).
*/
int recv_line(int sockfd, unsigned char *dest_buffer) {
#define EOL "\r\n" // End-of-line byte sequence
#define EOL_SIZE 2
unsigned char *ptr;
int eol_matched = 0;
ptr = dest_buffer;
while(recv(sockfd, ptr, 1, 0) == 1) { // Read a single byte.
if(*ptr == EOL[eol_matched]) { // Does this byte match terminator?
eol_matched++;
if(eol_matched == EOL_SIZE) { // If all bytes match terminator,
*(ptr+1-EOL_SIZE) = '\0'; // terminate the string.
return strlen(dest_buffer); // Return bytes received
}
} else {
eol_matched = 0;
}
ptr++; // Increment the pointer to the next byter.
}
return 0; // Didn't find the end-of-line characters.
}
Making a socket connection to a numerical IP address is pretty simple
but named addresses are commonly used for convenience. In the manual HTTP
HEAD request, the telnet program automatically does a DNS (Domain Name
Service) lookup to determine that www.internic.net translates to the IP address
192.0.34.161. DNS is a protocol that allows an IP address to be looked up by a
named address, similar to how a phone number can be looked up in a phone
book if you know the name. Naturally, there are socket-related functions and
structures specifically for hostname lookups via DNS. These functions and struc-
tures are defined in netdb.h. A function called gethostbyname() takes a pointer
to a string containing a named address and returns a pointer to a hostent
structure, or NULL pointer on error. The hostent structure is filled with infor-
mation from the lookup, including the numerical IP address as a 32-bit integer
in network byte order. Similar to the inet_ntoa() function, the memory for
this structure is statically allocated in the function. This structure is shown
below, as listed in netdb.h.
Search WWH ::




Custom Search