int main(int argc, char *argv[]) { int sockfd, portno; portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); struct addrinfo hints, *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; int status; if ((status = getaddrinfo(argv[1], argv[2], &hints, &res) != 0)) { // print error msg; exit(1); } connect(sockfd, res->ai_addr, res->ai_addrlen); // ... freeaddrinfo(res); // .... return 0; }
2. using gethostbyname()
int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) // print error msg here server = gethostbyname(argv[1]); if (server == NULL) { // print error msg...; exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); //..... return 0; }
No comments:
Post a Comment