当前位置: 技术问答>linux和unix
如何编程得到本机的IP?
来源: 互联网 发布时间:2015-08-22
本文导语: 如何编程得到本机的IP,不用ifconfig。谢谢! | char * get_local_ip(void) { int sock; struct sockaddr_in sin; struct ifreq ifr; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { perror("socket"); } strn...
如何编程得到本机的IP,不用ifconfig。谢谢!
|
char * get_local_ip(void)
{
int sock;
struct sockaddr_in sin;
struct ifreq ifr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
{
perror("socket");
}
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
if (ioctl(sock, SIOCGIFADDR, &ifr)
{
int sock;
struct sockaddr_in sin;
struct ifreq ifr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
{
perror("socket");
}
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
if (ioctl(sock, SIOCGIFADDR, &ifr)