Created
April 1, 2020 14:09
-
-
Save NicolasT/fe874b07cc84356e4197cf2f6f09904e to your computer and use it in GitHub Desktop.
Dumb Python implementation to get the IP address assigned to an interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import fcntl | |
import socket | |
import struct | |
''' | |
#include <stdio.h> | |
#include <net/if.h> | |
#include <netinet/in.h> | |
#include <sys/ioctl.h> | |
int main(int argc, char **argv) { | |
printf("IFNAMSIZ = %d\n", IFNAMSIZ); | |
printf("sizeof(struct ifreq) = %d\n", sizeof(struct ifreq)); | |
printf("SIOCGIFADDR = %d\n", SIOCGIFADDR); | |
printf("__builtin_offsetof(struct ifreq, ifr_addr) = %d\n", __builtin_offsetof(struct ifreq, ifr_addr)); | |
printf("__builtin_offsetof(struct sockaddr_in, sin_addr) = %d\n", __builtin_offsetof(struct sockaddr_in, sin_addr)); | |
printf("sizeof(struct in_addr) = %d\n", sizeof(struct in_addr)); | |
return 0; | |
} | |
''' | |
IFNAMSIZ = 16 | |
SIZEOF_IFREQ = 40 | |
SIOCGIFADDR = 35093 | |
OFFSETOF_IFR_ADDR = 16 | |
OFFSETOF_SIN_ADDR = 4 | |
SIZEOF_IN_ADDR = 4 | |
def get_address(name): | |
assert len(name) < IFNAMSIZ | |
req = struct.pack('{}s'.format(SIZEOF_IFREQ), name[:IFNAMSIZ - 1]) | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
try: | |
res = fcntl.ioctl(sock.fileno(), SIOCGIFADDR, req) | |
begin = OFFSETOF_IFR_ADDR + OFFSETOF_SIN_ADDR | |
end = begin + SIZEOF_IN_ADDR | |
ifr_addr = res[begin:end] | |
return socket.inet_ntoa(ifr_addr) | |
finally: | |
sock.close() | |
if __name__ == '__main__': | |
print(get_address(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment