The server side was shown in the example in "Connection-oriented server". You can clearly see the separate, asymmetric roles of the client and server in the program code. The server waits as a passive instance for connection requests from the client while the client initiates a connection as the active instance. The steps executed by the client process are looked at more closely in the following sections.
In the example program, the client uses the following socket or POSIX interface functions:
socket(): create socket
setsockopt(): set options for the socket
gethostbyname(): get the host name entry
connect(): request a connection on the socket
send(): write data to the socket
close(): close socket
Example: connection-oriented client
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <sys/uio.h> #define ERROR_EXIT(M) perror(M); exit(1) #define TESTPORT 2222 #define DATA "Here's the message ..." int main(int argc, char **argv) { int sock, length; struct sockaddr_in server; struct hostent *hp, *gethostbyname(); char buf[1024]; struct linger ling; ling.l_onoff = 1; ling.l_linger = 60; /* Create socket */ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { ERROR_EXIT("Create stream socket"); } /* Fill in the address structure */ server.sin_family = AF_INET; server.sin_port = htons(TESTPORT); if ((hp = gethostbyname(argv[1])) == NULL) { fprintf(stderr,"%s: unknown host\n", argv[1]); exit(1); } /* Start the connection */ memcpy((char *) &server.sin_addr, (char *)hp->h_addr, hp->h_length); if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) { ERROR_EXIT("Connect stream socket"); } /* Write to the socket */ if (send(sock, DATA, sizeof DATA, 0) < 0) { ERROR_EXIT("Write on stream socket"); } close(sock); return 0; }
The client creates a communications endpoint (socket) and the corresponding descriptor with the socket() function. The client gets the address of the host (the host name is passed as a parameter) with gethostbyname(). Then a connection is set up to the server on the specified host. The client initializes the address structure for this and the connection is set up with connect() function. After connection setup, data is written to the socket with the send() function. The socket is closed with the close() function.
The example program is only valid for the communications domain AF_INET. If it is modified according to the information in "Socket addressing" and "Creating a socket", it is also valid for the AF_INET6 domain. Please also make sure that you use the getaddrinfo() or getipnodebyname() functions instead of gethostbyname().