Skip to content

Commit

Permalink
Support search for host name and IP (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
mstmdev authored Oct 9, 2023
1 parent 0758cee commit 529e6be
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 11 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,18 @@

```bash
go install github.com/no-src/hosts/...@latest
```

## Usage

Print all host items.

```bash
$ hosts
```

Search for the specified hostname or IP, and multiple keywords are split with spaces.

```bash
$ hosts 192.168.100.1 github.com
```
15 changes: 15 additions & 0 deletions cmd/hosts/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

import (
"os"

"github.com/no-src/hosts"
)

func main() {
var search []string
if len(os.Args) > 1 {
search = os.Args[1:]
}
hosts.PrintHosts(search...)
}
9 changes: 0 additions & 9 deletions cmd/main.go

This file was deleted.

23 changes: 21 additions & 2 deletions hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func isWindows() bool {
}

// PrintHosts print the hosts info
func PrintHosts() {
func PrintHosts(search ...string) {
hostsFile := "/etc/hosts"
if isWindows() {
sysRoot := os.Getenv("SYSTEMROOT")
Expand Down Expand Up @@ -67,8 +67,27 @@ func PrintHosts() {
log.Log("-------------------------------------------------")
hosts = recombine(hosts)
for _, item := range hosts {
log.Log("%s %s", item.IP, strings.Join(item.HostNameList, " "))
var source []string
source = append(source, item.IP)
source = append(source, item.HostNameList...)
if find(source, search...) {
log.Log("%s %s", item.IP, strings.Join(item.HostNameList, " "))
}
}
}

func find(source []string, search ...string) bool {
if len(search) == 0 {
return true
}
for _, searchItem := range search {
for _, name := range source {
if strings.Contains(strings.ToLower(name), strings.ToLower(searchItem)) {
return true
}
}
}
return false
}

// recombine try to recombine hosts,group by ip and distinct,order by ip
Expand Down

0 comments on commit 529e6be

Please sign in to comment.