Open System Services Programmer's Guide
Example 44 Using AF_INET in an OSS Requester Process
/* requester2.c
*
* Simple OSS requester example using OSS socket APIs
* for communication between requester and server.
*
* This requester accepts terminal input and sends it to a
* server using a send() call and then waits for a response using
* a recv() call. When the server echoes the data back to the
* requester, the recv() call completes and the requester prompts
* for more terminal input. When terminal input ends with EOF,
* the socket connection is closed and the requester stops.
*/
#define _XOPEN_SOURCE_EXTENDED 1 /* needed for OSS sockets */
#include <unistd.h>
#include <fcntl.h>
#include <tal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netdb.h>
int fd, bytesread;
struct sockaddr_in addr; /* socket address (family,addr,port) */
#define BUFF_LEN 1024 /* data buffer length */
char msg_buff[BUFF_LEN+1]; /* data buffer */
int main(int argc, char **argv) {
printf("Requester starting\n");
/* create AF_INET stream socket ... if error, then exit(1) */
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket() call failed [errno %d]\n", errno);
exit(1);
}
/* Get server port from the command line or use default 12345 */
if (argc > 1)
addr.sin_port = (short)atoi(argv[1]); /* use command line arg */
else
addr.sin_port = 12345; /* use default */
addr.sin_family = AF_INET; /* internet address family */
addr.sin_addr.s_addr = gethostid(); /* assume server on our host */
/* connect to server ... if error, then exit(1) */
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
printf("connect() failed [errno %d]\n", errno);
exit(1);
}
/* Prompt user, read data, send data to server and wait for reply */
while (1) {
182 Interprocess Communication