int open_clientfdd(char *hostname,char *port){
int clientfd;
struct addrinfo hints,*listp,*p;
/* get a list of potential server address*/
memset(&hints,0,sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* open a connection */
hints.ai_flags = AI_NUMERICSERV; /* use a numeric prot arg */
hints.ai_flags |= AI_ADDRCONFIG; /* recommended for connections */
getaddrinfo(hostname,port,&hints,&listp);
/* walk the list for one that we can successfully connect to.*/
for(p = listp ; p; p = p->ai_next){
/* create a socket descriptor */
if((clientfd = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) < 0){
continue;
}
/* connect to the server*/
if(connect(clientfd,p->ai_addr,p->ai_addrlen) != -1 ){
break; /* connect success */
}
close(clientfd);
}
/* clean up */
freeaddrinfo(listp);
if(!p) /* all connects failed */
return -1;
else
return clientfd;
exit(0);
}
【c语言】打开一个客户端socket描述符
最新推荐文章于 2024-06-27 09:39:19 发布