分类:
2008-10-13 16:51:15
#include
#include
#include
#include
using namespace std;
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif
SOCKET sockconnect(char const * host, char const * service, char const * transport)
{
struct protoent * protoinfo;
struct sockaddr_in ipaddr;
struct hostent *hostinfo;
struct servent * servinfo;
int sock, type;
memset(&ipaddr, 0, sizeof(ipaddr));
ipaddr.sin_family = AF_INET;
//从服务器的服务类型得到端口号
if( (servinfo = getservbyname(service, transport)) != NULL){
ipaddr.sin_port = servinfo->s_port;
}else if((ipaddr.sin_port = htons ((u_short)atoi(service))) == 0){
cout << "get server information error " << endl;
WSACleanup();
exit(1);
}
//由传输协议得到其对应的传输协议编码
if((protoinfo = getprotobyname(transport)) == NULL)
{
cout << "get protocol information error " << endl;
WSACleanup();
exit(1);
}
//从主机名获取主机IP
if((hostinfo = gethostbyname(host)) != NULL){
memcpy(&ipaddr.sin_addr, hostinfo->h_addr, hostinfo->h_length);
}else if((ipaddr.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE){
cout << "get host IP information 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地址和端口,如果连接失败,则退出
//对于数据报类套接字,调用connect则设置一个缺省的目的地
if(connect(sock,(sockaddr*)&ipaddr,sizeof(ipaddr)) == SOCKET_ERROR){
cout << "connect sock error! please start server first. " << endl;
WSACleanup();
exit(1);
}
return sock;
}
SOCKET UDPConnect(char const * host, char const * service){
return sockconnect(host, service, "udp");
}
SOCKET TCPConnect(char const * host, char const * service){
return sockconnect(host, service, "tcp");
}