Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support search for host name and IP #7

Merged
merged 1 commit into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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