1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| /* 准备工作 */ #include<sys/types.h> #include<sys/socket.h>
#include<netinet/in.h> #include<arpa/inet.h>
#include<netdb.h> #include<string.h> #include<stdlib.h>
#ifndef INADDR_NONE #define INADDR_NONE 0xffffffff #endif
extern int errno;
int errexit(const char *format,...);
/* 函数变量定义 */ int connectsock(const char*host,const char*service,const char*transport) /* Arguments: host:name of host to which connection is desired service:service associated with the desired port transport:name of transport protocol to use("tcp" r "udp") */ { struct hostent *phe; struct servent *pse; struct protoent *ppe; struct sockaddr_in sin; int s,type;
memset(&sin,0,sizeof(sin)); sin.sin_family = AF_INET;
/* 取得端口号 */ if(pse = getservbyname(service,transport)) sin.sin_port = pse->s_port; else if((sin.sin_port=htons((unsigned short)atoi(service)))==0) errexit("can't get \"%s\" service entry\n",service);
/* 获取IP地址 */ if (phe = gethostbyname(host)) memcpy(&sin.sin_addr,phe->h_addr,phe->h_length); else if((sin.sin_addr.s_addr=inet_addr(host))==INADDR_NONE) errexit("can't get \"%s\" host entry\n",host);
/* 取得协议类型 */ if((ppe = getprotobyname(transport))==0) erreixt("can't get \"%s\" protocol entry\n",transport); if(strcmp(transport,"udp")==0) type = SOCK_DGRAM; else type = SOCK_STREAM;
/* 构成连接 */ s = socket(PF_INET,type,ppe->p_proto); if(s<0) errexit("can't create socket: %s\n",strerror(errno));
if(connect(s,(struct sockaddr*)&sin,sizeof(sin))<0) errexit("can't connect to %s.%s:%s\n",host,service,sterror(errno)); return s; }
|