netdb相關程式

主要是在建立socket時,會需要一些參數,而這些參數會存在系統中,可藉由下列fucntion查詢系統的設定檔,然後餵給socket API。

介紹如下的function:

struct hostent *gethostbyname(const char *name);

struct servent *getservbyname(const char *name, const char *proto);

  相關: struct servent *getservbyport(int port, const char *proto);

struct protoent *getprotobyname(const char *name);

  相關: struct protoent *getprotobynumber(int proto);

#include <netdb.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
    struct hostent *hp;
    struct servent *sp;
    struct protoent *pp;
    char ip[20];

    //related file: /etc/hosts
    hp=gethostbyname("www.nctu.edu.tw");
    if (hp==NULL)
    {
        printf("hp is null\n");
        return 1;
    }
    printf("hostname is %s, ip is %s\n",hp->h_name, (char *)inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]));

    //related file: /etc/services and /etc/nsswitch.conf

    //nsswitch.conf有關service的設定如下  services:       db files,其中files指的就是./etc/protocols
    sp = getservbyname("example", "udp");
    if (sp==NULL)
    {
        printf("sp is null\n");
        return 1;
    }

    //此處記得將s_port轉成network byte order,不然會印出奇怪的數字
    printf("service name is %s, port is %d\n",sp->s_name, htons(sp->s_port));

    //related file: /etc/protocols
    pp=getprotobyname("icmp");
    if (pp==NULL)
    {
        printf("pp is null\n");
        return 1;
    }
    printf("protocol name is %s,  number is %d\n",pp->p_name, pp->p_proto);

    return 0;

}

output如下:

latrell:~/temp/ctest$ gcc -g netdb.c -o netdb
latrell:~/temp/ctest$ ./netdb
hostname is www.nctu.edu.tw, ip is 140.113.40.36
service name is example, port is 22374
protocol name is icmp,  number is 1

 

 

kezeodsnx 發表在 痞客邦 PIXNET 留言(0) 人氣()