๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

TIL (Today I Learned)/Network

[TCP/IP] ๋ฌธ์ž์—ด ํ˜•์‹์˜ ๋„๋ฉ”์ธ -> 4๋ฐ”์ดํŠธ ๋„คํŠธ์›Œํฌ ๋ฐ”์ดํŠธ ์ˆœ์„œ๋กœ๋œ ์ด์ง„ ํ˜•์‹์˜ ์ฃผ์†Œ

728x90

๋ฌธ์ž์—ด ํ˜•์‹์˜ ๋„๋ฉ”์ธ -> 4๋ฐ”์ดํŠธ ๋„คํŠธ์›Œํฌ ๋ฐ”์ดํŠธ ์ˆœ์„œ๋กœ๋œ ์ด์ง„ ํ˜•์‹์˜ ์ฃผ์†Œ

ํ•จ์ˆ˜

#include <netdb.h>

struct hostent * gethostbyname(const char *name);

๋ฐ˜ํ™˜ ๊ฐ’

  • ์„ฑ๊ณต ์‹œ : hostent ๊ตฌ์กฐ์ฒด ์ฃผ์†Œ
  • ์‹คํŒจ ์‹œ : NULL

    ์ธ์ž

  • name : ๋„๋ฉ”์ธ ์ด๋ฆ„
    ์ธ์ž name์ด ๊ฐ€๋ฅดํ‚ค๋Š” ๋„๋ฉ”์ธ ์ด๋ฆ„์— ํ•ด๋‹นํ•˜๋Š” ์„œ๋ฒ„์˜ ์ •๋ณด๋ฅผ ๋„คํŠธ์›Œํฌ์ƒ์—์„œ ๊ฒ€์ƒ‰ํ•ด์„œ ๊ตฌ์กฐ์ฒด hostent์— ๋„ฃ์–ด ์ค€๋‹ค.

ํ•จ์ˆ˜

#include <netdb.h>

struct hostent * gethostnbyaddr(const char *addr, int len, int type);

๋ฐ˜ํ™˜ ๊ฐ’

  • ์„ฑ๊ณต ์‹œ : hostent ๊ตฌ์กฐ์ฒด ์ฃผ์†Œ
  • ์‹คํŒจ ์‹œ : NULL

    ์ธ์ž

  • addr : 32๋น„ํŠธ ์ด์ง„ ๊ฐ’์œผ IP ์ฃผ์†Œ
    len : ์ฃผ์†Œ ๊ธธ์ด
    type : ์ฃผ์†Œ ์œ ํ˜•

๊ตฌ์กฐ์ฒด

struct hostent {
  char *h_name;         // ๋„๋ฉ”์ธ ์ด๋ฆ„
  char **h_aliases;     // ๋ณ„๋ช…๋“ค
  int h_addrtype;       // ์ฃผ์†Œ ์œ ํ˜•
  int h_length;         // ์ฃผ์†Œ ๊ธธ์ด
  char **h_addr_list;   // ๋„คํŠธ์›Œํฌ ๋ฐ”์ดํŠธ ์ˆœ์„œ๋กœ ๋œ ์ด์ง„ ํ˜•์‹์˜ IP ์ฃผ์†Œ
}
#include<stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main() {
        struct in_addr addr;
        struct hostent *host;
        const char *hostName = "www.eluon.com";
        int i;

        if((host = gethostbyname(hostName)) == NULL ) {
                printf("gethostbyname() error - check network\n");
                exit(-1);
        }

        printf("official name = %s \n", host->h_name);

        for(i=0; host->h_aliases[i]; i++)
                printf("aliases %d : %s \n", i+1, host->h_aliases[i]);

        printf("address type = %d\n", host->h_addrtype);
        printf("address length = %d\n", host->h_length);

        i =0;
        while(host->h_addr_list[i] != NULL) {
                memcpy(&addr.s_addr, host->h_addr_list[i], 4);
                printf("address = %s(0x%x)\n", inet_ntoa(addr), ntohl(*(long*)host->h_addr_list[i]));
                i++;
        }
}

๊ฒฐ๊ณผํ™”๋ฉด

image