Skip to content

Commit

Permalink
fix linux codes
Browse files Browse the repository at this point in the history
  • Loading branch information
arcage committed Jan 9, 2019
1 parent 6416ee1 commit 47038c2
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 11 deletions.
16 changes: 12 additions & 4 deletions README.md
Expand Up @@ -2,9 +2,13 @@

This shard includes following sample codes.

- Gets hardware addresses(MAC address / phisical address) of the network interfaces.
- Gets following informations of the ethernet interfaces.

Implemented for linux(tested on CentOS7) and BSD(tested on Mac OS 10.14).
- hardware address a.k.a. MAC address or phisical address
- IPv4 address
- IPv6 address

_Implemented for linux(tested on CentOS7) and BSD(tested on Mac OS 10.14)._

- `ping` like command

Expand All @@ -27,8 +31,12 @@ dependencies:
```crystal
require "net_sample"
# get HW address from given network interface name
mac_of_eth1 = NetSample::HWAddr.hwaddr_of("eth1")
# get interface names
NetSample::NIC.ifnames
#=> ["lo0", "eth1"]
puts eth1 = NetSample::NIC["eth1"]
#=> <NIC: "eth1", inaddr: 192.0.2.100, in6addr: fe80::1234:abcd, hwaddr: aa:bb:cc:dd:ee:ff>
# ping like command(require root privirage)
NetSample::Ping.command("192.0.2.1")
Expand Down
10 changes: 7 additions & 3 deletions src/net_sample/nic.cr
Expand Up @@ -16,6 +16,10 @@ class NetSample::NIC
@@nics ||= get_nic_info
end

def self.ifnames
self.nics.keys
end

def self.inaddr_of(if_name)
self.nics[if_name]?.try &.inaddr
end
Expand Down Expand Up @@ -51,10 +55,10 @@ class NetSample::NIC

def to_s(io : IO)
io << "<NIC: " << @name.inspect
io << ", " << "inet: " << @inaddr if @inaddr
io << ", " << "inet6: " << @in6addr if @in6addr
io << ", " << "inaddr: " << @inaddr if @inaddr
io << ", " << "in6addr: " << @in6addr if @in6addr
if @hwaddr
io << ", " << "hw: "
io << ", " << "hwaddr: "
internal_hwaddr(io)
end
io << ">"
Expand Down
1 change: 1 addition & 0 deletions src/net_sample/nic/bsd.cr
Expand Up @@ -2,6 +2,7 @@

lib LibC
AF_LINK = 18
SDL_DATA_SIZE = 256

struct SockaddrDl
sdl_len : UChar
Expand Down
7 changes: 3 additions & 4 deletions src/net_sample/nic/linux.cr
Expand Up @@ -49,19 +49,18 @@ class NetSample::NIC
when LibC::AF_INET6
ina = ifa_addr.as(LibC::SockaddrIn6*).value
dst = StaticArray(UInt8, LibC::INET6_ADDRSTRLEN).new(0)
addr6 = ina.sin6_addr.__u6_addr.__u6_addr8
addr6 = ina.sin6_addr.__in6_u.__u6_addr8
LibC.inet_ntop(LibC::AF_INET6, addr6.to_unsafe.as(Void*), dst, LibC::INET6_ADDRSTRLEN)
nics[if_name].in6addr = String.new(dst.to_unsafe)
when LibC::AF_PACKET
lla = ifa_addr.as(LibC::SockaddrLl*).value
lla = String.new(data[0, LibC::IFHWADDRLEN])
data = lla.sll_addr.to_slice.clone
hwaddr = data[nlen, alen]
hwaddr = data[0, LibC::IFHWADDRLEN]
nics[if_name].hwaddr = hwaddr
end
end
ifap = ifa.ifa_next
end
nics
end
end
end

0 comments on commit 47038c2

Please sign in to comment.