如何得到本机的ip地址

ww7109 2004-03-25 10:35:24
我用gethostname 和 gethostbyname 两函数得到本机IP
地址,却总是得到127.0.0.1
请问如何得到本机IP地址
...全文
39 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bmw1981bmw 2004-03-25
  • 打赏
  • 举报
回复
^o^
ww7109 2004-03-25
  • 打赏
  • 举报
回复
sorry 无法结帖,给分
ww7109 2004-03-25
  • 打赏
  • 举报
回复
谢谢
bmw1981bmw 2004-03-25
  • 打赏
  • 举报
回复
先声明这些代码不是我自己写的,是以前本版的一个贴上的

一起感谢原作者

#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <signal.h>
#include <netinet/ip.h>

struct in_addr myself, mymask,broad;

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))) < 0) {
if ((fd_arp = socket(AF_INET,SOCK_STREAM,0)) < 0) {
perror( "arp socket error");
exit(-1);
}

strcpy(ifr.ifr_name, device);
/* ifr.ifr_addr.sa_family = AF_INET; */

/* get ip address of my interface */
if (ioctl(fd_arp, SIOCGIFADDR, &ifr) < 0) {
perror("ioctl SIOCGIFADDR error");
exit(-1);
}
sin_ptr = (struct sockaddr_in *)&ifr.ifr_addr;
myself = sin_ptr->sin_addr;

/* get network mask of my interface */
if (ioctl(fd_arp, SIOCGIFNETMASK, &ifr) < 0) {
perror("ioctl SIOCGIFNETMASK error");
exit(-1);
}
sin_ptr = (struct sockaddr_in *)&ifr.ifr_addr;
mymask = sin_ptr->sin_addr;

/* get broadcast addr of my interface */
if (ioctl(fd_arp, SIOCGIFBRDADDR, &ifr) < 0) {
perror("ioctl SIOCGIFNETMASK error");
exit(-1);
}
sin_ptr = (struct sockaddr_in *)&ifr.ifr_broadaddr;
broad = sin_ptr->sin_addr;


/* get mac address of the interface */
if (ioctl(fd_arp, SIOCGIFHWADDR, &ifr) < 0) {
perror("ioctl SIOCGIFHWADDR error");
exit(-1);
}
ptr = (u_char *)&ifr.ifr_ifru.ifru_hwaddr.sa_data[0];
printf( "request mac %02x:%02x:%02x:%02x:%02x:%02x\n ",
*ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3),
*(ptr + 4), *(ptr + 5) );
printf( "request netmask:%s \n", inet_ntoa(mymask));
printf( "request IP:%s\n", inet_ntoa(myself));
printf( "request broadcast:%s\n", inet_ntoa(broad));
exit(0);
}

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧