Ethernet.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package nmcli
  2. import (
  3. "AudioPlayer/nmcli/model"
  4. "context"
  5. nmcli_go "github.com/KunMengcode/nmcli-go"
  6. "github.com/KunMengcode/nmcli-go/connection"
  7. "net/rpc"
  8. "strings"
  9. )
  10. type EthernetInterface interface {
  11. SetStaticIP(Request model.EthernetStaticIPRequest, Reply *model.EmptyReply) error
  12. Show(Request model.DeviceInfoRequest, Reply *model.EthernetInfo) error
  13. register() error
  14. }
  15. type Ethernet struct {
  16. nmcli *nmcli_go.NMCli
  17. }
  18. func NewEthernet(nmcli *nmcli_go.NMCli) EthernetInterface {
  19. return &Ethernet{nmcli: nmcli}
  20. }
  21. func (receiver *Ethernet) register() error {
  22. return rpc.RegisterName("NetworkManager.Ethernet", receiver)
  23. }
  24. func (receiver *Ethernet) SetStaticIP(Request model.EthernetStaticIPRequest, Reply *model.EmptyReply) error {
  25. _, err := receiver.nmcli.Connection.Modify(context.Background(), false, Request.Id, map[string]string{
  26. "ipv4.addresses": Request.Ipv4Addresses,
  27. "ipv4.method": Request.Ipv4Method,
  28. "ipv4.dns": Request.DNS,
  29. "ipv4.gateway": Request.Gateway,
  30. })
  31. if err != nil {
  32. return err
  33. }
  34. _, err = receiver.nmcli.Connection.Up(context.Background(), Request.Id, connection.UpOptions{})
  35. if err != nil {
  36. return err
  37. }
  38. return nil
  39. }
  40. func (receiver *Ethernet) Show(Request model.DeviceInfoRequest, Reply *model.EthernetInfo) (err error) {
  41. if Request.DeviceInterfaceName == "" {
  42. Request.DeviceInterfaceName = "enp4s0"
  43. }
  44. show, err := receiver.nmcli.Device.Show(context.Background(), Request.DeviceInterfaceName)
  45. if err != nil {
  46. return err
  47. }
  48. *Reply = model.EthernetInfo{
  49. MacAddress: show[0]["GENERAL"][0][9],
  50. Ipv4Addresses: show[0]["IP4"][0][0],
  51. Gateway: show[0]["IP4"][0][1],
  52. DNS: strings.Split(show[0]["IP4"][0][3], "|"),
  53. }
  54. return nil
  55. }