s_socket.c
pdirt/drv/src/s_socket.c · 2.2 KB
From the archive pDirt-1_tar.gz
Download the archive « Back to the archive contents
#define S_SOCKET_C
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <fcntl.h>
#include "kernel.h"
#include "config.h"
#include "s_socket.h"
#include "log.h"
#include <unistd.h>
#include <string.h>
int make_service (short unsigned int port,
char *my_hostname,
int my_hostnamelen,
struct hostent **hp,
struct sockaddr_in *sin)
{
int s, i;
struct hostent *h;
if (gethostname (my_hostname, my_hostnamelen) < 0)
{
return -1; /* Error in hostname? */
}
if ((*hp = h = gethostbyname (my_hostname)) == NULL)
{
return -2; /* Error in gethostbyname */
}
bzero (sin, sizeof (struct sockaddr_in));
sin->sin_family = AF_INET;
sin->sin_port = htons (port);
bcopy ((char *) h->h_addr_list[0], (char *) (&(sin->sin_addr)), h->h_length);
if ((s = socket (AF_INET, SOCK_STREAM, 0)) < 0)
{
return -3; /* Error in socket call */
}
i = 2;
if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof (i)) == -1)
{
progerror ("setsockopt(reuseaddr)");
}
#if 0
/* Make service addition */
i = 58000;
if (setsockopt (s, SOL_SOCKET, SO_SNDBUF, &i, sizeof(i)) == -1)
{ progerror("setsockopt(sndbuf)");
}
#endif
if (bind (s, (struct sockaddr *)sin, sizeof (*sin)) < 0)
{
close (s);
return -4; /* Error in bind. */
}
if (listen (s, 5) != 0)
{
close (s);
return -5; /* Error in listen */
}
if (fcntl (s, F_SETFL, O_NDELAY) == -1)
{
close (s);
return -6; /* Error in fcntl */
}
return s;
}
int makesock(char *addr, int port)
{
int s, opt = 1;
struct hostent *host;
struct sockaddr_in client;
host = gethostbyname(addr);
if (!host) return(-1);
client.sin_family = AF_INET;
client.sin_port = htons(port);
client.sin_addr = (*(struct in_addr*)host->h_addr_list[0]);
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)) < 0)
{ close(s);
return -1;
}
if (connect(s, (struct sockaddr *) &client, sizeof(client)) == -1)
{ close(s);
return(-1);
}
if (fcntl(s, F_SETFL, O_NONBLOCK) == -1)
{ close(s);
return -1;
}
return(s);
}