诚石 » 日志 » Linux下面的socket编程,如何获得本机IP地址
Linux下面的socket编程,如何获得本机IP地址
Stone 发表于 2007-11-26 11:33:30
Linux下面的socket编程,如何获得本机IP地址
代码:
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int inet_sock;
struct ifreq ifr;
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
strcpy(ifr.ifr_name, "eth0");
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
perror("ioctl");
printf("%s\n", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
return 0;
}
Illidan 05-10-31 16:21
如果网卡不止一块,还可以用ioctl还做吗?
怎么知道网卡的数量呢?
小锁 05-10-31 18:38
代码:
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int inet_sock;
struct ifreq ifr;
FILE *net_devs;
char buf[1024];
char interface[32];
net_devs = fopen("/proc/net/dev", "r");
if(net_devs == NULL){
perror("Can't open /proc/net/dev for reading");
exit(1);
}
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
while(1){
if(fscanf(net_devs, "%32s %1024[^\n]", interface, buf) <= 0){
break;
}
if(interface[strlen(interface) - 1] != ':'){
continue; // skip the comment
}else{
interface[strlen(interface) - 1] = '#CONTENT#';
}
strcpy(ifr.ifr_name, interface);
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
perror("ioctl");
printf("%s:%s\n", interface,
inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
}
close(inet_sock);
return 0;
}
Illidan 05-11-01 15:42
试改如下,好像可以得到需要的结果:
代码:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
int main()
{
int inet_sock;
struct ifreq ifr;
FILE *net_devs;
char buf[1024];
char interface[32];
int index;
net_devs = fopen("/proc/net/dev", "r");
if(net_devs == NULL){
perror("Can't open /proc/net/dev for reading");
exit(1);
}
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
while(1){
if(fscanf(net_devs, "%32s %1024[^\n]", interface, buf) <= 0){
break;
}
index = 0;
while ( index<32 && interface[index] != ':' ) {
index++;
}
if (index>=32)
continue;
interface[index] = '#CONTENT#';
strcpy(ifr.ifr_name, interface);
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
perror("ioctl");
printf("%s:\t%s\n", interface,
inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
}
close(inet_sock);
return 0;
}
