有地址转换函数gethostbyname、gethostbyaddr、getservbyname、getservbyport,请选择其中三个进行举例应用
时间: 2024-01-02 14:02:13 浏览: 78
getservbyname
4星 · 用户满意度95%
1. gethostbyname:该函数通过主机名获取主机的IP地址。例如:
```
#include <stdio.h>
#include <netdb.h>
int main() {
const char *hostname = "www.google.com";
struct hostent *host = gethostbyname(hostname);
if (host == NULL) {
printf("gethostbyname failed\n");
return 1;
}
printf("%s's IP address is %s\n", hostname, host->h_addr_list[0]);
return 0;
}
```
2. gethostbyaddr:该函数通过IP地址获取主机名和其他相关信息。例如:
```
#include <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>
int main() {
const char *ip = "8.8.8.8";
struct in_addr addr;
if (inet_aton(ip, &addr) == 0) {
printf("inet_aton failed\n");
return 1;
}
struct hostent *host = gethostbyaddr(&addr, sizeof(addr), AF_INET);
if (host == NULL) {
printf("gethostbyaddr failed\n");
return 1;
}
printf("%s's hostname is %s\n", ip, host->h_name);
return 0;
}
```
3. getservbyname:该函数通过服务名获取服务的端口号。例如:
```
#include <stdio.h>
#include <netdb.h>
int main() {
const char *servname = "http";
struct servent *serv = getservbyname(servname, "tcp");
if (serv == NULL) {
printf("getservbyname failed\n");
return 1;
}
printf("%s's port number is %d\n", servname, ntohs(serv->s_port));
return 0;
}
```
阅读全文