/*下面是服务端的连接的初始化函数,
SOCKET sockserver(const char *service,const char *transport,int qlen)
SOCKET TCPserver(const char * service,int qlen)
SOCKET UDPserver(const char * service,int qlen)
直接调用下面三个函数,就可以对socket 进行初始化,
有了它,我们进行socket 编程非常的方面
笔者还作了客户端的函数,及网络编程的例子,如有需要者,请E-mail:cangzhu@163.com
*/
#include "stdlib.h"
#include "winsock.h"
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif
SOCKET sockserver(const char *service,const char *transport,int qlen)
{
strUCt protoent *protoin;
struct sockaddr_in ipaddr;
struct servent *servin;
int type;
SOCKET sock;
memset(&ipaddr,0,sizeof(ipaddr));
ipaddr.sin_family=AF_INET;
ipaddr.sin_addr.s_addr=INADDR_ANY;
if(servin=getservbyname(service,transport))
ipaddr.sin_port=ntohs((u_short)servin->s_port);
else
if((ipaddr.sin_port=htons((u_short)atoi(service)))==0)
{
printf("get portnum error");
WSACleanup();
getchar();
exit(1);
}
if((protoin=getprotobyname(transport))==0)
{
printf("get protocol error");
WSACleanup();
getchar();
exit(1);
}
if(strcmp(transport,"udp")==0)
type=SOCK_DGRAM;
else
type=SOCK_STREAM;
sock=socket(PF_INET,type,protoin->p_proto);
if(sock==INVALID_SOCKET)
{
printf("create socket error");
WSACleanup();
getchar();
exit(1);
}
if(bind(sock,(struct sockaddr*)&ipaddr,sizeof(ipaddr))==SOCKET_ERROR)
{
printf("sock bind error");
WSACleanup();
getchar();
exit(1);
}
if(type==SOCK_STREAM)
{
if(listen(sock,qlen)==SOCKET_ERROR)
{
printf("sock bind error");
WSACleanup();
getchar();
exit(1);
}
}
return sock;
}
SOCKET TCPserver(const char * service,int qlen)
{
return sockserver(service,"tcp",qlen);
}
SOCKET UDPserver(const char * service,int qlen)
{
return sockserver(service,"udp",qlen);
}