要在基于Debian的系统上以编程方式获取IP地址,您可以使用以下方法:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
int main() {
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) {
if (ifa->ifa_addr == NULL)
continue;
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\n", gai_strerror(s));
continue;
}
printf("Interface: %s\tIPv4 address: %s\n", ifa->ifa_name, host);
} else if (family == AF_INET6) {
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0) {
printf("getnameinfo() failed: %s\n", gai_strerror(s));
continue;
}
printf("Interface: %s\tIPv6 address: %s\n", ifa->ifa_name, host);
}
}
freeifaddrs(ifaddr);
return 0;
}
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15].encode('utf-8')))
return socket.inet_ntoa(info[20:24])
print(get_ip_address('eth0'))
这些方法都可以在基于Debian的系统上以编程方式获取IP地址。您可以根据您的需求和编程语言选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云