当前位置: 技术问答>linux和unix
获取IP的问题
来源: 互联网 发布时间:2015-11-30
本文导语: 在不同平台上获取ip有的成功,有的失败。我在网上搜索了一下,看到如下说明: 用gethostname()/gethostbyname()依赖于本机的域名解析系统,比如/etc/hosts文件、/etc/nsswitch.conf文件、/etc/resolv.conf文件。这样获取本机IP是不...
在不同平台上获取ip有的成功,有的失败。我在网上搜索了一下,看到如下说明:
用gethostname()/gethostbyname()依赖于本机的域名解析系统,比如/etc/hosts文件、/etc/nsswitch.conf文件、/etc/resolv.conf文件。这样获取本机IP是不可靠的。
如果/etc/hosts文件中没有指定本机IP,则依赖DNS是否配置了PTR资源记录。可靠的办法应该是strace ifconfig、truss ifconfig,实际就是照ifconfig的实现去获取本机IP。
但是不明白,编程如何实现呢?
谢谢!
用gethostname()/gethostbyname()依赖于本机的域名解析系统,比如/etc/hosts文件、/etc/nsswitch.conf文件、/etc/resolv.conf文件。这样获取本机IP是不可靠的。
如果/etc/hosts文件中没有指定本机IP,则依赖DNS是否配置了PTR资源记录。可靠的办法应该是strace ifconfig、truss ifconfig,实际就是照ifconfig的实现去获取本机IP。
但是不明白,编程如何实现呢?
谢谢!
|
的确这样, 不同的系统方法的确不同.
在linux, 用strace跟踪了ifconfig eth0可以看到
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
ioctl(3, SIOCGIFCONF, 0xbffff674) = 0
ioctl(3, SIOCGIFFLAGS, 0xbffff63c) = 0
ioctl(3, SIOCGIFADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFHWADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFMETRIC, 0xbffff63c) = 0
ioctl(3, SIOCGIFMTU, 0xbffff63c) = 0
ioctl(3, SIOCGIFDSTADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFBRDADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFNETMASK, 0xbffff63c) = 0
这样的字样, 说明ifconfig使用的ioctl来获得"设备"的IP地址.
下面是个例程, 可以在Linux下获得eth0上面的IP.
注意, 这点代码只能用于linux。FreeBSD上略有不同,要和sysctl配合使用.
有关详细情况和复杂操作, 还请参考UNP, man文档(和Linux上的ifconfig源码).
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
struct in_addr myself, mymask;
int fd_arp; /* socket fd for receive packets */
struct ifreq ifr; /* ifr structure */
main (int argc, char* argv[]) {
char device[32]; /* ethernet device name */
struct sockaddr from, to;
int fromlen;
struct sockaddr_in *sin_ptr;
u_char *ptr;
int n;
strcpy(device, "eth0");
if ((fd_arp = socket(AF_INET, SOCK_PACKET, htons(0x0806)))
在linux, 用strace跟踪了ifconfig eth0可以看到
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
ioctl(3, SIOCGIFCONF, 0xbffff674) = 0
ioctl(3, SIOCGIFFLAGS, 0xbffff63c) = 0
ioctl(3, SIOCGIFADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFHWADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFMETRIC, 0xbffff63c) = 0
ioctl(3, SIOCGIFMTU, 0xbffff63c) = 0
ioctl(3, SIOCGIFDSTADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFBRDADDR, 0xbffff63c) = 0
ioctl(3, SIOCGIFNETMASK, 0xbffff63c) = 0
这样的字样, 说明ifconfig使用的ioctl来获得"设备"的IP地址.
下面是个例程, 可以在Linux下获得eth0上面的IP.
注意, 这点代码只能用于linux。FreeBSD上略有不同,要和sysctl配合使用.
有关详细情况和复杂操作, 还请参考UNP, man文档(和Linux上的ifconfig源码).
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
struct in_addr myself, mymask;
int fd_arp; /* socket fd for receive packets */
struct ifreq ifr; /* ifr structure */
main (int argc, char* argv[]) {
char device[32]; /* ethernet device name */
struct sockaddr from, to;
int fromlen;
struct sockaddr_in *sin_ptr;
u_char *ptr;
int n;
strcpy(device, "eth0");
if ((fd_arp = socket(AF_INET, SOCK_PACKET, htons(0x0806)))