Chinaunix首页 | 论坛 | 博客
  • 博客访问: 578288
  • 博文数量: 752
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-13 14:47
文章分类

全部博文(752)

文章存档

2011年(1)

2008年(751)

我的朋友

分类:

2008-10-13 16:51:16

#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");
}


--------------------next---------------------

阅读(282) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~