(转载)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;
}

相关文章:

  • 2021-12-24
  • 2021-09-13
  • 2022-01-13
  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2021-05-25
  • 2022-12-23
相关资源
相似解决方案