(转载)Linux上编程获取本机IP地址(而不是127.0.0.1)

(转载)http://blog.sina.com.cn/s/blog_4065d7370100075l.html

具体代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys pes.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <net/route.h>
#include <string.h>

int get_my_address (struct in_addr *addr)
{
    struct ifreq req;
    int sock;

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    strncpy (req.ifr_name, "eth0", IFNAMSIZ);

    if ( ioctl(sock, SIOCGIFADDR, &req) < 0 )
    {
        printf("failed to ioctl: %s\n", strerror (errno));
        return 0;
    }

    memcpy (addr, &((struct sockaddr_in *) &req.ifr_addr)->sin_addr, sizeof (struct in_addr));
    return 1;
}


int main(int argc, char *argv[])
{

  struct in_addr addr;
  char ip[32];

  if(get_my_address(&addr))
  {
      //strncpy(ip, inet_ntoa(addr), sizeof(struct in_addr));
      printf("IP Address : %s\n",inet_ntoa(addr));
  }

 

  return 0;
}

posted @ 2013-05-03 10:34  robotke1  阅读(795)  评论(0编辑  收藏  举报