type TSunB = packed record s_b1, s_b2, s_b3, s_b4: Byte; end;
TSunW = packed record s_w1, s_w2: Word; end;
PIn4Addr = ^TIn4Addr; TIn4Addr = packed record case integer of 0: (S_un_b: TSunB); 1: (S_un_w: TSunW); 2: (S_addr: LongWord); end;
PIn6Addr = ^TIn6Addr; TIn6Addr = packed record case Integer of 0: (s6_addr: packed array [0..16-1] of Byte); 1: (s6_addr16: packed array [0..8-1] of Word); end;
function IPv4AddrToString(const aInAddr: TIn4Addr): string; begin Result := IntToStr(TIn4Addr(AInAddr).S_un_b.s_b1) + '.' {Do not Localize} + IntToStr(TIn4Addr(AInAddr).S_un_b.s_b2) + '.' {Do not Localize} + IntToStr(TIn4Addr(AInAddr).S_un_b.s_b3) + '.' {Do not Localize} + IntToStr(TIn4Addr(AInAddr).S_un_b.s_b4); end;
// 获取本地mac function getLocalMac(var sIP: string): string; {$IFDEF POSIX} const MAXINTERFACES = 15; var sock_fd: integer; buf: array[0..MAXINTERFACES-1] of ifreq; ifc: ifconf; interface_num: integer; //M: TMarshaller; //sEn: string; {$ENDIF} begin {$IFDEF POSIX} sIP := ''; Result := '';
sock_fd := socket(AF_INET, SOCK_DGRAM, //SOCK_STREAM, 0); if (sock_fd = -1) then begin //perror('create socket falise...mac\n'); Exit; end;
if(ioctl(sock_fd, SIOCGIFCONF, @ifc) < 0) then begin Exit; end; interface_num := ifc.ifc_len div sizeof(ifreq);
while interface_num>0 do begin Dec(interface_num);
sIP := ''; Result := '';
if (ioctl(sock_fd, SIOCGIFFLAGS, @buf[interface_num])<0) then begin Continue; end; (* if(buf[interface_num].ifr_flags & IFF_PROMISC) printf("Interface is in promiscuous mode\n"); *) if ((buf[interface_num].ifr_ifru.ifru_flags and IFF_UP)<>0) and ((buf[interface_num].ifr_ifru.ifru_flags and IFF_RUNNING)<>0)and ((buf[interface_num].ifr_ifru.ifru_flags and IFF_LOOPBACK)=0) then //printf("Interface is running\n"); else Continue; //printf("Interface is not running\n");
//IP地址 if (ioctl(sock_fd, SIOCGIFADDR, @buf[interface_num])<0) then begin Continue; end; if buf[interface_num].ifr_ifru.ifru_addr.sa_family<>AF_INET then //AF_INET6 Continue; sIP := IPv4AddrToString( TIn4Addr(sockaddr_in(buf[interface_num].ifr_ifru.ifru_addr).sin_addr));
//MAC地址 if ((ioctl(sock_fd, SIOCGIFHWADDR, @buf[interface_num])) < 0) then begin //printf('mac ioctl error\n'); Result := ''; Continue; end;