#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> #include <netdb.h> const int maxline=4096; int main(int argc, char **argv) { int sockfd, n; char recvline[maxline+1], errbuff[maxline];; struct sockaddr_in servaddr; struct in_addr **pptr; struct in_addr *inetaddrp[2]; struct in_addr inetaddr; struct hostent *hp; struct servent *sp; if(argc!=3) { fprintf(stderr, "usage: daytimetcpcli <hostname> <service>\n"); exit(-1); } if((hp=gethostbyname(argv[1])) == NULL) { if(inet_aton(argv[1], &inetaddr)==0) { fprintf(stderr, "hostname error for %s: %s\n", argv[1], hstrerror(h_errno)); exit(-1); } else { inetaddrp[0]=&inetaddr; inetaddrp[1]=NULL; pptr=inetaddrp; } } else { pptr=(struct in_addr **)hp->h_addr_list; } if((sp=getservbyname(argv[2], "tcp")) == NULL) { fprintf(stderr, "getservbyname error for %s\n", argv[2]); exit(-1); } for(; *pptr!=NULL; pptr++) { if((sockfd=socket(AF_INET, SOCK_STREAM, 0))<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "socket error: %s\n", errbuff); exit(-1); } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=sp->s_port; memcpy(&servaddr.sin_addr, *pptr, sizeof(struct in_addr)); printf("trying %s: %d\n", inet_ntop(AF_INET, &servaddr.sin_addr, errbuff, sizeof(errbuff)), ntohs(servaddr.sin_port)); if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))==0) { break; } else { strerror_r(errno, errbuff, maxline); fprintf(stderr, "connect error: %s\n", errbuff); close(sockfd); exit(-1); } } if(*pptr==NULL) { fprintf(stderr, "unable to connect!\n"); exit(-1); } while((n=read(sockfd, recvline, maxline))>0) { recvline[n]=0; if(fputs(recvline, stdout)==EOF) { fprintf(stderr, "fputs error\n"); exit(-1); } } if(n<0) { fprintf(stderr, "read error.\n"); exit(-1); } exit(0); }
标签:addr,pptr,gethostbyname,fprintf,IP地址,exit,include,服务端,struct From: https://www.cnblogs.com/donggongdechen/p/16719044.html