linux c函数获取系统IP地址

一,通过分析/etc/hosts文件里映射关系获取ip地址。
#include <stdio.h>
#include <netdb.h>
int main()
{
        struct hostent *he;
        char hostname[20] = {0};

        gethostname(hostname,sizeof(hostname));
        he = gethostbyname(hostname);
        printf("hostname=%s\n",hostname);
        printf("%s\n",inet_ntoa(*(struct in_addr*)(he->h_addr)));
}

二,通过ioctl()函数
下表列出了网络相关ioctl请求的request 参数以及arg 地址必须指向的数据类型:

  

类别 Request 说明 数据类型


SIOCATMARK 
SIOCSPGRP 
SIOCGPGRP
是否位于带外标记 
设置套接口的进程ID 或进程组ID 
获取套接口的进程ID 或进程组ID
int 
int 
int

FIONBIN 
FIOASYNC 
FIONREAD 
FIOSETOWN 
FIOGETOWN
设置/ 清除非阻塞I/O 标志 
设置/ 清除信号驱动异步I/O 标志 
获取接收缓存区中的字节数 
设置文件的进程ID 或进程组ID 
获取文件的进程ID 或进程组ID
int 
int 
int 
int 
int

SIOCGIFCONF 
SIOCSIFADDR 
SIOCGIFADDR 
SIOCSIFFLAGS 
SIOCGIFFLAGS 
SIOCSIFDSTADDR 
SIOCGIFDSTADDR 
SIOCGIFBRDADDR 
SIOCSIFBRDADDR 
SIOCGIFNETMASK 
SIOCSIFNETMASK 
SIOCGIFMETRIC 
SIOCSIFMETRIC 
SIOCGIFMTU 
SIOCxxx
获取所有接口的清单 
设置接口地址 
获取接口地址 
设置接口标志 
获取接口标志 
设置点到点地址 
获取点到点地址 
获取广播地址 
设置广播地址 
获取子网掩码 
设置子网掩码 
获取接口的测度 
设置接口的测度 
获取接口MTU 
(还有很多取决于系统的实现)
struct ifconf 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq 
struct ifreq
ARP SIOCSARP 
SIOCGARP 
SIOCDARP
创建/ 修改ARP 表项 
获取ARP 表项 
删除ARP 表项
struct arpreq 
struct arpreq 
struct arpreq

SIOCADDRT 
SIOCDELRT
增加路径 
删除路径
struct rtentry 
struct rtentry
I_xxx    

#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
        int inet_sock;
        struct ifreq ifr;
        inet_sock = socket(AF_INET, SOCK_DGRAM, 0);

        strcpy(ifr.ifr_name, "eth0");
        //SIOCGIFADDR标志代表获取接口地址
        if (ioctl(inet_sock, SIOCGIFADDR, &ifr) <  0)
                perror("ioctl");
        printf("%s\n", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
        return 0;
}

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值