- #include <netdb.h>
- #include <arpa/inet.h>
- using namespace std;
- int main() {
- int result = 0;
- char hostName[100];
- struct hostent* host = NULL;
- result = gethostname(hostName, 100);
- host = gethostbyname(hostName);
- char* ip =inet_ntoa(*((struct in_addr *)host->h_addr_list[0]));
- cout<< "hostname:" << hostName << ", ip:" << ip << endl;
- return 1;
- }
解析:
- struct hostent
- {
- char* h_name; //主机的规范名
- char** h_aliases; //主机的别名
- int h_addrtype; //主机ip地址类型, AF_INET为ipv4, AF_INET6为ipv6
- int h_length; //主机ip地址长度
- char** h_addr_list; //主机的ip地址,网络字节序
- }
- char* inet_ntoa(struct in_addr) //将网络字节序ip地址转为字符串
- struct in_addr {
- in_addr_t s_addr;
- };