A number of support routines are included. There are functions to convert hostnames to IP (Internet Protocol) addresses and other network nameserver services. There are routines provided for simple conversions of integers to a network format for inter-machine communication. Conversions of more complex data types to a machine neutral format can be done with the XDR (external data representation) library.
Sockets is a low level mechanism with a correspondingly low level API. This allows for a large amount of control, but it also means that a large number of steps are needed to perform operations. The procedure required to send a message using TCP is
The code to perform this procedure is shown in figure 5. Notice that error checking has to be performed at all steps of the process to ensure that the program does not terminate.
Sockets is best used for high performance bulk transfer applications. The only language binding commonly used is C although some of the scripting languages, such as Perl, encapsulate some of the features of sockets.
There is no standard security mechanism built into sockets at this time although the SSL (Socket Security Layer) proposal [SSL] is gaining wide support. SSL was originally developed for use in WWW browsers to allow secure money transactions.
// client.cpp
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stream.h>
#include <rpc/types.h>
#include <rpc/xdr.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char** argv) {
struct hostent* host;
struct sockaddr_in addr;
int value, svalue;
char buff[ 32];
int sock;
XDR xdr;
if( argc != 3) {
cerr << "usage: client host value\n";
return 1; }
sock = socket( AF_INET, SOCK_STREAM, 0); // create the socket
if( sock == -1) {
cerr << "client can not create socket\n";
return 1; }
addr.sin_family = AF_INET; // get the host address
host = gethostbyname( argv[1]);
if( !host) {
cerr << "can not find host " << argv[1] << endl;
close( sock);
return 1; }
// fill in the address
memcpy( (char*) &addr.sin_addr, (char*) host->h_addr, host->h_length);
addr.sin_port = htons( 2000); // fill in the destination port
// make a TCP connection
if( connect( sock, (struct sockaddr*) &addr, sizeof addr) == -1) {
cerr << "client can not connect to server\n";
close( sock);
return 1; }
value = atoi( argv[2]); // create the data for a simple packet
svalue = value * value;
//create the XDR stream
xdrmem_create( &xdr, buff, 32, XDR_ENCODE);
xdr_int( &xdr, &value); // encode the data
xdr_int( &xdr, &svalue);
write( sock, buff, 32); // send the data packet
close( sock); // clean up
return 0;
}