The difference between a Client Socket and a Server Socket is:
A client Socket does an Aktive Connection.
A Server Socker waits passive for a Connection
The routines below have been tested with Windows NT and the C++-Builder, but special
C++ features are not used.
With small modifications they could be used in Unix environments.
#define NR_CONNECTIONS 3 // Maximum Number of allowed Connections Max 5
// could be passed to the routine as an Argument too
int tcp_accept(char *service,int port,char *emsg,unsigned int dllhandle)
/***********************************************************************
service Service Name in the Service Table (required if Port = 0)
Port Port Number Required if service = empty
emsg Error Message (char[60] should be enough)
dllhandle Handle to winsock.dll (see netinit in Faq creating a Client socket)
************************************************************************/
{
unsigned long inaddr;
unsigned char hostname[20];
unsigned char buffer[4];
servent *sp;
int is;
hostent *hp;
sockaddr_in tcp_srv_addr;
int fd;
// Define DLL-Functions
struct servent FAR * PASCAL (FAR *gsbyname)(const char FAR* ,const char FAR *);
u_short PASCAL (FAR *htns) (u_short FAR);
struct hostent FAR * PASCAL (FAR *ghbyname)(const char FAR * name);
SOCKET PASCAL (FAR *sckt) (int FAR, int FAR, int FAR);
int PASCAL (FAR *bind) (SOCKET s,const struct sockaddr FAR *, int namelen);
int PASCAL (FAR *lstn) (SOCKET FAR, int backlog);
int PASCAL (FAR *ghsn) (char *, int len);
// If there is a Service number
{
if(port<=0)
{
sprintf(emsg,"tcp_open: must specify either service or port\n");
return SERVICE_MISSING;
}
tcp_srv_addr.sin_port=(*htns)(port);
}
// define Socket as a listener
// NR_Connections gives the maximum allowed # of pending Connections.
// if there are more requests, the connections are refused.
// wait for a connection
// On this place usually there should be a way to get the IP-Address from the connecting
// host. The array saddr.sa_data[2] contains the IP of the connecting Host
// Create a independent Copy (fd1) of Socket fd
le = sizeof(saddr)
if((fd1=(*acpt)(fd,saddr,&le))>0)
{
// If connection is ok create a new thread and pass handle fd1 to the the server function(netserver)
// in this function everything is handled. Don't forget to close all sockets after use
ih=(unsigned long *)CreateThread(NULL,0,netserver,fd1,0,&serverid);
}
// You can use the Handle fd1 like it is used on a Client Socket.
}
return 0;
}
Don't forget to close the socket after use by closesocket.
Closesocket is encapsulated in winsock.dll.
It is called:
CloseSocket(fd); where fd is a handle to the Socket (int)
The initilization is equivalent to the other winsock-functions.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.