Advertisement
Guest User

Untitled

a guest
Apr 25th, 2018
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <netdb.h>
  6. #include <string.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #include <sys/socket.h>
  10. #include <limits.h>
  11. #include <netdb.h>
  12.  
  13.  
  14. enum
  15. {
  16.     MAX_NAME_SIZE = 2000
  17. };
  18.  
  19.  
  20. int main() {
  21.     char host[MAX_NAME_SIZE], service[MAX_NAME_SIZE];
  22.     while (scanf("%s %s", host, service) != EOF) {
  23.         struct addrinfo *infoptr;
  24.         struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM };
  25.  
  26.         int err = getaddrinfo(host, service, &hints, &infoptr);
  27.         if (err) {
  28.             printf("%s\n", gai_strerror(err));
  29.             fflush(stdout);
  30.         } else {
  31.             struct sockaddr_in* min_saddr = NULL;
  32.             unsigned long int min_local_bytes = ULONG_MAX;
  33.  
  34.             struct addrinfo *p;    
  35.             for(p = infoptr; p != NULL; p = p->ai_next) {
  36.                 struct sockaddr_in* saddr = (struct sockaddr_in*)p->ai_addr;
  37.                 if (min_local_bytes >= ntohl(saddr->sin_addr.s_addr)) {
  38.                     min_saddr = saddr;
  39.                     min_local_bytes = ntohl(saddr->sin_addr.s_addr);
  40.                 }
  41.             }
  42.  
  43.             printf("%s:%hu\n", inet_ntoa(min_saddr->sin_addr), ntohs(min_saddr->sin_port));
  44.             fflush(stdout);
  45.             freeaddrinfo(infoptr);
  46.         }
  47.     }
  48.    
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement