linux 获取IP函数

一,通过分析/etc/hosts文件里映射关系获取ip地址。
#include
#include
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
#include
#include
#include
#include
#include
#include
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;
}

你可能感兴趣的:(c语言,linux,TCPIP)