本地接口和ip
枚举本地接口和ip在ip_helper.h和ip_helper_generic.c
/**
* Enumerate the local IP interfaces currently active in the host.
*
* @param af Family of the address to be retrieved. Application
* may specify pj_AF_UNSPEC() to retrieve all addresses,
* or pj_AF_INET() or pj_AF_INET6() to retrieve interfaces
* with specific address family.
* @param count On input, specify the number of entries. On output,
* it will be filled with the actual number of entries.
* @param ifs Array of socket addresses, which address part will
* be filled with the interface address. The address
* family part will be initialized with the address
* family of the IP address.
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_enum_ip_interface(int af,
unsigned *count,
pj_sockaddr ifs[]);
根据编译选项有4种实现方式:
1、使用getifaddrs
这种方式对IPv4和IPv6都有效,推荐使用。返回ifaddrs结构体,描述接口信息,其中ifa_next可以遍历接口,ifa_addr是ip地址。
struct ifaddrs
{
struct ifaddrs *ifa_next; /* Next item in list */
char *ifa_name; /* Name of interface */
unsigned int ifa_flags; /* Flags from SIOCGIFFLAGS */
struct sockaddr *ifa_addr; /* Address of interface */
struct sockaddr *ifa_netmask; /* Netmask of interface */
union
{
struct sockaddr *ifu_broadaddr; /* Broadcast address of interface */
struct sockaddr *ifu_dstaddr; /* Point-to-point destination address */
} ifa_ifu;
#define ifa_broadaddr ifa_ifu.ifu_broadaddr
#define ifa_dstaddr ifa_ifu.ifu_dstaddr
void *ifa_data; /* Address-specific data */
};
freeifaddrs(ifap);
2、使用ifconf和ifreq,再配合ioctrl,这种方式不支持IPv6。
//ifconf通常是用来保存所有接口信息的
//if.h
struct ifconf
{
int ifc_len; /* size of buffer */
union
{
char *ifcu_buf; /* input from user->kernel*/
struct ifreq *ifcu_req; /* return from kernel->user*/
} ifc_ifcu;
};
#define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */
#define ifc_req ifc_ifcu.ifcu_req /* array of structures */
//ifreq用来保存某个接口的信息
//if.h
struct ifreq
{
char ifr_name[IFNAMSIZ];
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
short ifru_flags;
int ifru_metric;
caddr_t ifru_data;
} ifr_ifru;
};
#define ifr_addr ifr_ifru.ifru_addr
#define ifr_dstaddr ifr_ifru.ifru_dstaddr
#define ifr_broadaddr ifr_ifru.ifru_broadaddr
1. 先通过ioctl获得本地所有接口的信息,并保存在ifconf中
2. 再从ifconf中取出每一个ifreq中表示ip地址的信息
具体使用时我们可以认为ifconf就有两个成员:
ifc_len 和ifc_buf, 如图一所示:
ifc_len:表示用来存放所有接口信息的缓冲区长度
ifc_buf:表示存放接口信息的缓冲区
所以我们需要在程序开始时对ifconf的ifc_len和ifc_buf进行初始化
接下来使用ioctl获取所有接口信息,完成后ifc_len内存放实际获得的接口信息总长度
并且信息被存放在ifc_buf中。
如下图示:(假设读到两个接口信息)
ioctrl常用的操作
SIOCGIFCONF
SIOCGIFFLAGS
SIOCGIFADDR
SIOCGIFNETMASK
3、使用if_nameindex和ifreq
struct if_nameindex
{
unsigned int if_index; //网卡索引
char *if_name; 网卡名称
};
if_nameindex()
if_freenameindex(if_list)
if_nameindex可以扫描所有接口,然后同样使用ioctrl获取地址。和2差不多,只不过使用if_nameindex代替ifconf
4、使用pjlib封装的接口
/* Just get one default route */
status = pj_getdefaultipinterface(af, &ifs[0]);