Listing 3: Function openSock
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int openSock(char *hostName, int httpPort)
{
int skt;
struct sockaddr_in sktin;
struct hostent *host;
/* allocate a socket */
if ((skt = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{ fprintf(stderr, "*Error - can't create socket\n");
exit(1);
}
memset(&sktin, 0, sizeof(sktin));
sktin.sin_family = AF_INET;
/* set port number for http */
sktin.sin_port = htons(httpPort);
/* map host name to ip address */
if (host = gethostbyname(hostName))
memcpy(&sktin.sin_addr, host->h_addr, host->h_length);
else if ((sktin.sin_addr.s_addr = inet_addr(hostName))
< 0) /* dotted dec */
{ fprintf(stderr,
"*Error - can't get host entry for %s\n", hostName);
exit(1);
}
/* connect the socket */
if (connect(skt, &sktin, sizeof(sktin)) < 0)
{ fprintf(stderr,
"*Error - can't connect to %s:%d\n", hostName, httpPort);
exit(1);
}
return(skt);
}
/* End of File */