Be open to learning new lessons even if they contradict the lessons you learned yesterday.--------敞开心胸学习新的东西,即使他与你昨天学到的互相矛盾。
1, 预备知识
我们平常往往都是通过网站的域名上网,那我们如何使用程序获取相应服务器的公网IP呢?
今天我们就编写这么一个程序。
关键在gethostbyname()
函数,下面是结构体:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
}
如果忘记了命令函解析,可以阅读:
https://blog.csdn.net/weixin_46027505/article/details/104430092
2, 不含命令函解析的代码
- 我们先编写一个不含命令行解析的baidu.c 用于解析百度的ip地址
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>
#define web "baidu.com"
int main(int argc, char *argv[])
{
struct hostent *p;
int i;
char *serv_ip = NULL;
p = gethostbyname(web);
printf("domai name: %s\n", p->h_name);
//接收一个in_addr结构体类型的参数并返回一个以点分十进制格式表示的IP地址字符串
serv_ip = inet_ntoa(*(struct in_addr*)p->h_addr);
printf("serv_ip: %s\n", serv_ip);
return 0;
}
3, 含命令行解析的代码
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>
int main(int argc, char *argv[])
{
int ch=0;
struct hostent *p;
int i;
char *serv_ip = NULL;
struct option opts[] =
{
{"domain_name", required_argument, NULL, 'd'},
{0, 0, 0, 0}
};
while( (ch=getopt_long(argc, argv, "d:", opts, NULL)) != -1 )
{
switch(ch)
{
case 'd':
serv_ip=optarg;
break;
}
}
p = gethostbyname(serv_ip);
printf("domai name: %s\n", p->h_name);
printf("\n");
//打印所有ip地址
for (i = 0; p->h_addr_list[i]; i++)
{
printf("ip address: %s \n", inet_ntoa(*(struct in_addr *)p->h_addr_list[i]));
}
printf("\n");
serv_ip = inet_ntoa(*(struct in_addr*)p->h_addr);
printf("serv_ip: %s\n", serv_ip);
return 0;
}