linux 網絡通信地址查詢api

#include <netdb.h>
struct hostent* gethostent(void);

作用:返回本機主機信息。該函數讀取/etc/hosts,逐行返回此文件中內容,即多次調用每次返回不同值,不可重入,示例:

struct hostent* p;
p = gethostent();
while (p) {
    printf("%s\n", p->h_name);
    p = gethostent();
}
struct protoent* getprotoent(void)

作用:返回協議信息。該函數讀取/etc/protocols,逐行返回此文件中內容,示例:

struct protoent* p;
p = getprotoent();
while (p) {
    printf("%s\n", p->p_name);
    p = getprotoent();
}
struct servent* getservent(void)

作用:返回服務名。該函數讀取/etc/services,逐行返回文件內容,示例:

struct servent* p;
p = getservent();
while (p) {
    printf("%s\n", p->s_name);
    p = getservent();
}
#include <sys/typs.h>
#include <sys/socket.h>
#include <netdb.h>

int getaddrinfo(
    const char* node,
    const char* service,
    const struct adddrinfo* hints,
    struct adddrinfo** res);

作用:整合上述單個函數的功能,提供一個一次獲取所有信息的接口,同時此函數是線程安全的,示例:

struct addrinfo* p;
struct addrinfo hint;
hint.ai_flags = AI_CANONNAME;
getaddrinfo("localhost", "telnet", &hint, &p);
for (struct addrinfo* ploop = p; ploop; ploop = ploop->ai_next) {
    printf("%s\n", ploop->ai_canonname);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章