Get ip address from hostname in C using Linux sockets

Here are 2 methods to get the ip address of a hostname :

The first method uses the traditional gethostbyname function to retrieve information about a hostname/domain name.
Code

1 #include<stdio.h> //printf
2 #include<string.h> //memset
3 #include<stdlib.h> //for exit(0);
4 #include<sys/socket.h>
5 #include<errno.h> //For errno - the error number
6 #include<netdb.h> //hostent
7 #include<arpa/inet.h>
8  
9 int hostname_to_ip(char *  , char *);
10  
11 int main(int argc , char *argv[])
12 {
13     if(argc <2)
14     {
15         printf("Please provide a hostname to resolve");
16         exit(1);
17     }
18      
19     char *hostname = argv[1];
20     char ip[100];
21      
22     hostname_to_ip(hostname , ip);
23     printf("%s resolved to %s" , hostname , ip);
24      
25     printf("\n");
26      
27 }
28 /*
29     Get ip from domain name
30  */
31  
32 int hostname_to_ip(char * hostname , char* ip)
33 {
34     struct hostent *he;
35     struct in_addr **addr_list;
36     int i;
37          
38     if ( (he = gethostbyname( hostname ) ) == NULL)
39     {
40         // get the host info
41         herror("gethostbyname");
42         return 1;
43     }
44  
45     addr_list = (struct in_addr **) he->h_addr_list;
46      
47     for(i = 0; addr_list[i] != NULL; i++)
48     {
49         //Return the first one;
50         strcpy(ip , inet_ntoa(*addr_list[i]) );
51         return 0;
52     }
53      
54     return 1;
55 }

Compile and Run

1 $ gcc hostname_to_ip.c && ./a.out www.google.com
2 www.google.com resolved to 74.125.235.16
3  
4 $ gcc hostname_to_ip.c && ./a.out www.msn.com
5 www.msn.com resolved to 207.46.140.34
6  
7 $ gcc hostname_to_ip.c && ./a.out www.yahoo.com
8 www.yahoo.com resolved to 98.137.149.56

The second method uses the getaddrinfo function to retrieve information about a hostname/domain name.
Code

1 #include<stdio.h> //printf
2 #include<string.h> //memset
3 #include<stdlib.h> //for exit(0);
4 #include<sys/socket.h>
5 #include<errno.h> //For errno - the error number
6 #include<netdb.h> //hostent
7 #include<arpa/inet.h>
8  
9 int hostname_to_ip(char *  , char *);
10  
11 int main(int argc , char *argv[])
12 {
13     if(argc <2)
14     {
15         printf("Please provide a hostname to resolve");
16         exit(1);
17     }
18      
19     char *hostname = argv[1];
20     char ip[100];
21      
22     hostname_to_ip(hostname , ip);
23     printf("%s resolved to %s" , hostname , ip);
24      
25     printf("\n");
26      
27 }
28 /*
29     Get ip from domain name
30  */
31  
32 int hostname_to_ip(char *hostname , char *ip)
33 {
34     int sockfd; 
35     struct addrinfo hints, *servinfo, *p;
36     struct sockaddr_in *h;
37     int rv;
38  
39     memset(&hints, 0, sizeof hints);
40     hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
41     hints.ai_socktype = SOCK_STREAM;
42  
43     if ( (rv = getaddrinfo( hostname , "http" , &hints , &servinfo)) != 0)
44     {
45         fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
46         return 1;
47     }
48  
49     // loop through all the results and connect to the first we can
50     for(p = servinfo; p != NULL; p = p->ai_next)
51     {
52         h = (struct sockaddr_in *) p->ai_addr;
53         strcpy(ip , inet_ntoa( h->sin_addr ) );
54     }
55      
56     freeaddrinfo(servinfo); // all done with this structure
57     return 0;
58 }

Compile and Run

1 $ gcc hostname_to_ip.c && ./a.out www.google.com
2 www.google.com resolved to 74.125.235.19
3  
4 $ gcc hostname_to_ip.c && ./a.out www.yahoo.com
5 www.yahoo.com resolved to 72.30.2.43
6  
7 $ gcc hostname_to_ip.c && ./a.out www.msn.com
8 www.msn.com resolved to 207.46.140.34
时间: 2024-11-01 10:30:22

Get ip address from hostname in C using Linux sockets的相关文章

POJ 2105 IP Address (strtoll函数)

Time Limit: 1000MS Memory Limit: 30000K Description Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of '1s' and '0s' (bits) to a dotted decimal format. A dotted de

[J2MEQ&amp;A]WTK初始化WMAClient报错XXX has no IP address的解释

[J2ME]WTK初始化WMAClient报错XXX has no IP address的解释   [现象] 当通过WTK运行一个J2ME程序时,KToolbar显示这样的错误: 错误形态一 WMAClient: localhost has no IP address: java.net.UnknownHostException: xxxx: xxxx Warning: Failed to initialize WMA message routing support ClientConnecto

获取本机外网IP地址(External IP Address)示例

原文:http://www.cnblogs.com/Csharpblogs/articles/2218156.html import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Matcher; import

Virtual IP Address的实现

VIP在HA的使用 目前的互联网业务对服务器的依赖度极高,几乎不能容忍非计划的停机.但是机器的故障是无法100%避免的,所以,出现了HA技术,使用冗余的来保证服务可用. 但是,光有冗余还不行,还需要检测故障,故障切换. 目前的流程就是: 正常情况时,灾备系统只是监控服务器的运行. 服务器宕机,灾备系统发现故障. 灾备系统把流量切换到备份服务器. VIP就是用在最后一步,它保证了灾备切换的透明.因为IP无需改变. 一种VIP实现方法 有一种方法就是通过ARP协议实现VIP,因为在数据链路层,数据帧

Virtual IP address

只是翻译一下维基百科的内容. 概念 虚拟IP地址(VIP或VIPA)是一个IP地址指向多个应用程序驻留的单个服务器,多个域名,或者多个服务器,而不是被指向一个特定的服务器或网卡(NIC).传入的数据包会发送到虚拟地址并路由到真实的网络接口. 一个服务器IP地址依赖于网卡上的MAC地址.并且每一个逻辑IP地址只能指向一个网卡.然而,VIP地址能够让若干不同应用和虚拟应用的服务器集合只使用一个逻辑IP地址. VIP有若干变化和实现场景,包括通用地址冗余协议(CARP)和代理地址解析协议(proxy

POJ 2105 IP Address

Problem Description Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of '1s' and '0s' (bits) to a dotted decimal format. A dotted decimal format for an IP address i

The host file--map a name to an IP address

The host file is located at \windows\system32\drivers\etc\* and the format is ----------------------------------------------------------------------------------------------------------------- # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sa

poj 2105 IP Address【模板 power2】

这道题就是一个字符串处理的问题... 一次AC,很爽... #include <stdio.h> char IP[35]; //存放最开始的二进制数 int address[5]; //存放最后的答案 int power2(int n) { //自己写的2的次方 int i; int result=1; for (i=0;i<n;i++) result<<=1; //不停 *2 return result; } //将二进制转成4个十进制 void work() { int

虚拟机克隆,并设置新的ip,配置hostname,配合hostname,hosts

6.1克隆新的虚拟机 选中某个虚拟机-à右键à管理à克隆 选择下一步 选择下一步 点击完成   6.2修改主机名 [root@hadoop3 ~]# vim /etc/sysconfig/network 将文件中的HOSTNAME改成hadoop3,下面可以只需要下面两行 重新登录   6.3修改vi /etc/udev/rules.d/70-persistent-net.rules中的内容 留下最后一行,并且把最后的eth1改成eth0 6.4.修改ip 命令是:vim /etc/syscon