您的位置:首页 > 理论基础 > 计算机网络

unix网络编程之根据主机名(hostname)或网卡名获取IP地址(三种方法)

2016-01-05 13:42 696 查看
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>

//使用getaddrinfo函数,根据hostname获取IP地址
int getIpAddrByHostname_1(char *hostname, char *ip_str, size_t ip_size)
{
struct addrinfo *result = NULL, hints;
int ret = -1;

memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
ret = getaddrinfo(hostname, NULL, &hints, &result);

if (ret == 0)
{
struct in_addr addr = ((struct sockaddr_in *)result->ai_addr)->sin_addr;
const char *re_ntop = inet_ntop(AF_INET, &addr, ip_str, ip_size);
if (re_ntop == NULL)
ret = -1;
}

freeaddrinfo(result);
return ret;
}

//使用ping指令,根据hostname获取ip地址
int getIpAddrByHostname_2(char *hostname, char* ip_addr, size_t ip_size)
{
char command[256];
FILE *f;
char *ip_pos;

snprintf(command, 256, "ping -c1 %s | head -n 1 | sed 's/^[^(]*(\\([^)]*\\).*$/\\1/'", hostname);
fprintf(stdout, "%s\n", command);
if ((f = popen(command, "r")) == NULL)
{
fprintf(stderr, "could not open the command, \"%s\", %s\n", command, strerror(errno));
return -1;
}

fgets(ip_addr, ip_size, f);
fclose(f);

ip_pos = ip_addr;
for (;*ip_pos && *ip_pos!= '\n'; ip_pos++);
*ip_pos = 0;

return 0;
}

//使用ioctl,根据网卡名获取IP地址
int getIpAddrByEthName(char *eth_name, char* ip_addr, size_t ip_size)
{
int sock;
struct sockaddr_in sin;
struct ifreq ifr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
{
perror("socket");
return -1;
}

strncpy(ifr.ifr_name, eth_name, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
{
perror("ioctl");
return -1;
}

memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
strcpy(ip_addr, inet_ntoa(sin.sin_addr));

return 0;
}

int main()
{
char addr[64] = {0};
getIpAddrByHostname_1("localhost", addr, INET_ADDRSTRLEN);
fprintf(stdout, "localhost: %s\n", addr);

getIpAddrByHostname_2("localhost", addr, INET_ADDRSTRLEN);
fprintf(stdout, "localhost: %s\n", addr);

getIpAddrByEthName("eth0", addr, INET_ADDRSTRLEN);
fprintf(stdout, "eth0: %s\n", addr);

return 0;
}


相关参考:http://blog.csdn.net/prettyshuang/article/details/50457086
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: