我如何利用C码获得当地机器的IP地址?
如果存在多个接口,我就应当能够展示每个接口的IP地址。
<>光> 在C法典中不使用任何指令,如config,以检索IP地址。
我如何利用C码获得当地机器的IP地址?
如果存在多个接口,我就应当能够展示每个接口的IP地址。
<>光> 在C法典中不使用任何指令,如config,以检索IP地址。
用户s/149530/michael-foukarakis” Michael Foukarakis 我能够在同一机器上向各种接口展示IP地址:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
family = ifa->ifa_addr->sa_family;
if (family == AF_INET) {
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0) {
printf("getnameinfo() failed: %s
", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("<Interface>: %s <Address> %s
", ifa->ifa_name, host);
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
int main()
{
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
snprintf(ifr.ifr_name, IFNAMSIZ, "eth0");
ioctl(fd, SIOCGIFADDR, &ifr);
/* and more importantly */
printf("%s
", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
close(fd);
}
如果你要列举所有接口,请看getifaddrs(
)的功能——如果你重新回到了短链氯化石蜡。
了解“proc/net/dev”的所有接口。 注:它不能只使用电离线进行所有接口。
#define PROC_NETDEV "/proc/net/dev"
fp = fopen(PROC_NETDEV, "r");
while (NULL != fgets(buf, sizeof buf, fp)) {
s = strchr(buf, : );
*s = ;
s = buf;
// Filter all space here
got one interface name here, continue for others
}
fclose(fp);
然后用电线(Octl)():
struct ifreq ifr;
struct ifreq ifr_copy;
struct sockaddr_in *sin;
for each interface name {
strncpy(ifr.ifr_name, ifi->name, sizeof(ifr.ifr_name) - 1);
ifr_copy = ifr;
ioctl(fd, SIOCGIFFLAGS, &ifr_copy);
ifi->flags = ifr_copy.ifr_flags;
ioctl(fd, SIOCGIFADDR, &ifr_copy);
sin = (struct sockaddr_in*)&ifr_copy.ifr_addr;
ifi->addr = allocating address memory here
bzero(ifi->addr, sizeof *ifi->addr);
*(struct sockaddr_in*)ifi->addr = *sin;
/* Here also you could get netmask and hwaddr. */
}