69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <arpa/inet.h>
int connectSock(const char *host,const char *service , const char *transport)
{
struct sockaddr_in sa;
struct hostent *hp;
struct servent *sp;
struct protoent *ppe;
u_short portbase;
int s;
int type;
memset(&sa,0,sizeof(sa));
sa.sin_family = AF_INET;
if((hp = gethostbyname(host))==NULL){
fprintf(stderr,"%s: no such host?\n", host);
exit(1);
}
bcopy((char*)hp->h_addr, (char*)&sa.sin_addr, hp->h_length);
if((sp = getservbyname(service,transport))==NULL){
fprintf(stderr,"%s: No such service on this host\n");
exit(1);
}
portbase =9000;
sa.sin_port = htons((u_short)atoi(service)+portbase);
if((ppe = getprotobyname(transport))==0){
perror("can't get this protocol entry\n");
exit(1);
}
if (strcmp(transport, "udp")==0)
type = SOCK_DGRAM;
else type = SOCK_STREAM;
if((s=socket(PF_INET, type ,ppe->p_proto))<0){
perror("socket");
exit(1);
}
if(connect(s,(struct sockaddr*)&sa,sizeof sa)<0){
perror("connect");
exit(1);
}
return s;
}