分类:
2008-10-13 16:51:16
#include
#include
#include
#include
#include
using namespace std;
SOCKET sockserver(char const* service,char const* transport,int qlen)
{
struct sockaddr_in ipaddr; //主机IP地址
struct servent * servinfo; //服务器信息
struct protoent* protoinfo; //传输类型信息
int sock,type; //套接字描述符
memset(&ipaddr, 0, sizeof(ipaddr));
ipaddr.sin_family = AF_INET;
ipaddr.sin_addr.s_addr = INADDR_ANY;
//从服务名得到服务端口
if(servinfo=getservbyname(service,transport))
ipaddr.sin_port = htons(ntohs((u_short)servinfo->s_port));
else if((ipaddr.sin_port=htons((u_short)atoi(service)))==0){
cout<< "Get portnumber error \n" <
exit(1);
}
//从传输协议名得到对应编号
if((protoinfo = getprotobyname(transport)) == 0){
cout << "get proto naumber error" << endl;
WSACleanup();
exit(1);
}
//根据传输协议给对应变量赋值
if(strcmp(transport,"udp") == 0){
type = SOCK_DGRAM;
}else{
type = SOCK_STREAM;
}
//创建套接字
sock = socket(AF_INET,type,protoinfo->p_proto);
if(sock == INVALID_SOCKET){
cout << "create socket error" << endl;
WSACleanup();
exit(1);
}
//绑定本地IP地址
if(bind(sock,(sockaddr *)&ipaddr,sizeof(ipaddr))==SOCKET_ERROR){
cout << "socket bind error" << endl;
WSACleanup();
exit(1);
}
//如果是流式套接字,则使套接字处于监听状态
if(type == SOCK_STREAM){
if(listen(sock,qlen)==SOCKET_ERROR){
cout << "socket listen error" << endl;
WSACleanup();
exit(1);
}
}
return sock;
}
SOCKET UDPServer(char const * service){
return sockserver(service,"udp",0);
}
SOCKET TCPServer(char const * service,int qlen){
return sockserver(service,"tcp",qlen);
}