func (x *Imp) Defined(s string) bool { // x.Clr() if x.fmt == Hostname { if ip, err := net.LookupHost(s); err == nil { x.ip = net.ParseIP(ip[0]) // default for _, n := range ip { // get first IPv4-number, if such exists if len(n) == 4 { x.ip = net.ParseIP(n) break } } if h, err1 := net.LookupAddr(s); err1 == nil { x.name = h } else { x.name = []string{s} } return true } } else { // x.fmt == IPnumber if h, err := net.LookupAddr(s); err == nil { x.ip = net.ParseIP(s) x.name = h return true } } return false }
// Return the current machines fully qualified domain name. func Fqdn() (string, error) { hostname, err := os.Hostname() if err != nil { return "", err } addrs, err := net.LookupHost(hostname) if err != nil { return "", err } for _, addr := range addrs { names, err := net.LookupAddr(addr) if err != nil { return "", err } for _, name := range names { if strings.Contains(name, ".") { return name, nil } } } return hostname, nil }
// ServeHTTP is an http.Handler ServeHTTP method func (h *bandwidthQuotaHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { host, _, _ := net.SplitHostPort(req.RemoteAddr) longIP := longIP{net.ParseIP(host)}.IptoUint32() if h.quotas.WillExceedQuota(longIP, req.ContentLength) { hosts, _ := net.LookupAddr(uint32ToIP(longIP).String()) log.Debug.Printf("Offending Host: %s, BandwidthUsed: %d", hosts, h.quotas.GetQuotaUsed(longIP)) writeErrorResponse(w, req, BandWidthInsufficientToProceed, req.URL.Path) return } qr := "aReader{ ReadCloser: req.Body, quotas: h.quotas, ip: longIP, w: w, req: req, lock: &sync.RWMutex{}, } req.Body = qr w = "aWriter{ ResponseWriter: w, quotas: h.quotas, ip: longIP, quotaReader: qr, } h.handler.ServeHTTP(w, req) }
func (milter *milter) Connect(ctx uintptr, hostname string, ip net.IP) (sfsistat int8) { defer milterHandleError(ctx, &sfsistat) sess := &milterSession{ id: milterGetNewSessionId(), timeStart: time.Now(), persisted: false, } sess.Hostname = hostname sess.Ip = ip.String() sess.MtaHostName = m.GetSymVal(ctx, "j") sess.MtaDaemonName = m.GetSymVal(ctx, "{daemon_name}") if reverse, _ := net.LookupAddr(ip.String()); len(reverse) != 0 { sess.ReverseDns = reverse[0] } MilterDataIndex.addNewSession(sess) sessId := sess.getId() res := m.SetPriv(ctx, sessId) if res != 0 { panic(fmt.Sprintf("Session could not be stored in milterDataIndex")) } StatsCounters["MilterCallbackConnect"].increase(1) Log.Debug("%s Milter.Connect() called: ip = %s, hostname = %s", sess.milterGetDisplayId(), ip, sess.ReverseDns) return m.Continue }
func lookupAddr(ip net.IP) ([]string, error) { names, err := net.LookupAddr(ip.String()) for i, _ := range names { names[i] = strings.TrimRight(names[i], ".") // Always return unrooted name } return names, err }
func TestPingMonitor(t *testing.T) { conn, _ := rados.NewConn() conn.ReadDefaultConfigFile() conn.Connect() // mon id that should work with vstart.sh reply, err := conn.PingMonitor("a") if err == nil { assert.NotEqual(t, reply, "") return } // mon id that should work with micro-osd.sh reply, err = conn.PingMonitor("0") if err == nil { assert.NotEqual(t, reply, "") return } // try to use a hostname as the monitor id mon_addr, _ := conn.GetConfigOption("mon_host") hosts, _ := net.LookupAddr(mon_addr) for _, host := range hosts { reply, err := conn.PingMonitor(host) if err == nil { assert.NotEqual(t, reply, "") return } } t.Error("Could not find a valid monitor id") conn.Shutdown() }
func (a *API) requestFilter(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ip, err := ipFromRequest(r) if err != nil { r.Header.Set(IP_HEADER, err.Error()) } else { r.Header.Set(IP_HEADER, ip.String()) country, err := a.lookupCountry(ip) if err != nil { r.Header.Set(COUNTRY_HEADER, err.Error()) } else { r.Header.Set(COUNTRY_HEADER, country) } } hostname, err := net.LookupAddr(ip.String()) if err != nil { r.Header.Set(HOSTNAME_HEADER, err.Error()) } else { r.Header.Set(HOSTNAME_HEADER, strings.Join(hostname, ", ")) } if a.CORS { w.Header().Set("Access-Control-Allow-Methods", "GET") w.Header().Set("Access-Control-Allow-Origin", "*") } next.ServeHTTP(w, r) }) }
func getIP(s string) string { a, err := net.LookupAddr(s) if err != nil { return "" } return a[0] }
func LookupAddress(ip string) chan string { r := make(chan string) go func() { names, error := net.LookupAddr(ip) if error != nil { // Error? Use the IP. r <- ip } if len(names) > 0 { // Use the first value, but strip the leading ".". host := names[0] l := len(host) if host[l-1] == '.' { r <- host[0 : l-1] } else { r <- host } } else { // Use the IP r <- ip } }() return r }
func (info *Info) SetBasicInfo(url string, response *http.Response) { info.Url = url for key, values := range response.Header { info.RawHeaders[key] = values } cookies := response.Cookies() for _, cookie := range cookies { info.Cookies[cookie.Name] = cookie } u, err := urlLib.Parse(url) if err != nil { panic(err) } info.Host = u.Host ips, err := net.LookupHost(u.Host) if err == nil { info.Ip = ips for _, ip := range info.Ip { hosts, err := net.LookupAddr(ip) if err == nil { info.RealHost = hosts } } } }
func (msg milterMessage) String() []byte { sess := *msg.getSession() fqdn, err := os.Hostname() if err != nil { Log.Error("Could not determine FQDN") fqdn = sess.getMtaHostName() } revdns, err := net.LookupAddr(sess.getIp()) revdnsStr := "unknown" if err == nil { revdnsStr = strings.Join(revdns, "") } body := make([]string, 0) body = append(body, fmt.Sprintf("Received: from %s (%s [%s])\r\n\tby %s with SMTP id %d@%s; %s\r\n", sess.getHelo(), revdnsStr, sess.getIp(), fqdn, sess.getId(), fqdn, time.Now().Format(time.RFC1123Z))) for _, header := range msg.getHeaders() { body = append(body, (*header).getKey()+": "+(*header).getValue()+"\r\n") } body = append(body, "\r\n") for _, bodyChunk := range msg.getBody() { body = append(body, bodyChunk) } return []byte(strings.Join(body, "")) }
func getHostNamesFromIP(ip string) ([]string, error) { hostNames, err := net.LookupAddr(ip) if err != nil { return nil, err } return hostNames, nil }
func NewConn(p *PeerConnection) (*Conn, error) { c := &Conn{ Host: p.Host, Port: p.Port, conn: p.Conn, } names, err := net.LookupAddr(c.Host) if err == nil { c.Resolved = names[0] } else { c.Resolved = "No reverse DNS possible" } if c.conn == nil { var err error if c.conn, err = net.DialTimeout("tcp", c.String(), peerTimeout); err != nil { return c, fmt.Errorf("Connect: %s", err.Error()) } } config := &sslconn.Config{ CipherList: defaultCipher, } if c.Conn, err = sslconn.NewConn(c.conn, c.conn, config, false); err != nil { return c, fmt.Errorf("Connect: %s", err.Error()) } if err := c.Handshake(); err != nil { return c, fmt.Errorf("Connect: %s", err.Error()) } return c, nil }
func handlePost(w http.ResponseWriter, req *http.Request) { logRequest(req) author, _, _ := net.SplitHostPort(req.RemoteAddr) addrs, err := net.LookupAddr(author) if err != nil && len(addrs) > 0 { author = addrs[0] } title := req.FormValue("title") text := req.FormValue("text") title = strings.TrimSpace(title) text = strings.TrimSpace(text) if title == "" || text == "" { err = fmt.Errorf("empty title or text") logError(w, req, http.StatusBadRequest, err) return } post := Post{ Title: title, Text: text, Author: author, When: time.Now(), } err = savePost(post) if err != nil { logError(w, req, http.StatusInternalServerError, err) return } w.Write([]byte("OK")) }
// Resolve an IP to a domain name using the system DNS settings first, then HypeDNS func resolveIP(ip string) (hostname string, err error) { var try2 string // try the system DNS setup result, _ := net.LookupAddr(ip) if len(result) > 0 { goto end } // Try HypeDNS try2, err = reverseHypeDNSLookup(ip) if try2 == "" || err != nil { err = fmt.Errorf("Unable to resolve IP address. This is usually caused by not having a route to hypedns. Please try again in a few seconds.") return } result = append(result, try2) end: for _, addr := range result { hostname = addr } // Trim the trailing period becuase it annoys me if hostname[len(hostname)-1] == '.' { hostname = hostname[:len(hostname)-1] } return }
func lookupHosts(ips []net.IP) []string { set := map[string]struct{}{} for _, ip := range ips { txt, err := ip.MarshalText() if err != nil { continue } hosts, err := net.LookupAddr(string(txt)) debugf("lookup %v => %v, %v", string(txt), hosts, err) if err != nil { continue } for _, host := range hosts { h := strings.ToLower(strings.TrimSuffix(host, ".")) set[h] = struct{}{} } } hosts := make([]string, 0, len(set)) for host := range set { hosts = append(hosts, host) } return hosts }
func NameFromIP(addr string) string { names, err := net.LookupAddr(addr) if err != nil { return "" } return names[0] }
func LookupByAddressAndUserAgent(address string, useragent string, providers []Provider) LookupResult { addr, err := net.LookupAddr(address) if err != nil { fmt.Println(err) os.Exit(1) } result := LookupResult{IsBot: false} for _, provider := range providers { if useragent != "" { if provider.IdentifiesAsBot(useragent) { result.BotName = provider.Name() result.IdentifiesAsBot = true } } if provider.IsBot(addr) { result.BotName = provider.Name() result.IsBot = true return result } } return result }
/** * This retrieves the local host name * @return the local host name */ func GetLocalHostName() (hostName string) { var logger = NewPrefixed("utility#GetLocalHostName") hostName = "" if hostaddrs, err := net.InterfaceAddrs(); err == nil { for _, addr := range hostaddrs { logger.Finest("Addr = %v", addr.String()) ip, _, _ := net.ParseCIDR(addr.String()) logger.Finest("IP = %v", ip.String()) hostnames, _ := net.LookupAddr(ip.String()) if len(hostnames) < 1 { continue } for _, name := range hostnames { logger.Finest("hostname = %v", name) if len(hostName) < 1 || strings.Contains(hostName, "localhost") { hostName = name } else { if len(name) > 0 && !strings.Contains(name, "localhost") { hostName = name } } } } } if (len(hostName) > 0) && (hostName[len(hostName)-1] == '.') { hostName = hostName[:len(hostName)-1] } return hostName }
/*Hostname returns the hostname of the given IP address if available, or the IP address otherwise. If the hostname is found, the IP address is also appended in parentheses.*/ func Hostname(ip net.IP) string { names, err := net.LookupAddr(ip.String()) if err != nil || len(names) == 0 { return ip.String() } return fmt.Sprintf("%s (%s)", names[0], ip.String()) }
// IsGoogleBot - Checks if given IP address is really Google Bot IP address. func IsGoogleBot(addr string) (yes bool, err error) { addrs, err := net.LookupAddr(addr) if err != nil || len(addrs) == 0 { return } yes = strings.HasSuffix(addrs[0], ".googlebot.com.") return }
func revIP(ip string) { ptr, _ := net.LookupAddr(ip) ptrs := "" for _, v := range ptr { ptrs += "," + v } fmt.Printf("%s%s\n", ip, ptrs) }
func traceOne(addr *syscall.SockaddrInet4, ttl int) *ReturnArgs { cli, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP) if err != nil { exitWithError(err) } srv, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP) if err != nil { exitWithError(err) } defer syscall.Close(cli) defer syscall.Close(srv) // set ttl, stolen from somewhere else... // https://github.com/aeden/traceroute/blob/master/traceroute.go#L195 if err := syscall.SetsockoptInt(cli, syscall.SOL_IP, syscall.IP_TTL, ttl); err != nil { exitWithError(err) } // set timeout, stolen from somewhere else... // https://github.com/aeden/traceroute/blob/master/traceroute.go#L197 tv := syscall.NsecToTimeval(1e6 * TIMEOUT) if err := syscall.SetsockoptTimeval(srv, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv); err != nil { exitWithError(err) } if err := syscall.Bind(srv, toAddr(HOST, RECV_PORT)); err != nil { exitWithError(err) } rr := &ReturnArgs{} start := time.Now() if err := syscall.Sendto(cli, makeICMP(), 0, addr); err != nil { return rr } buf := make([]byte, 512) _, from, err := syscall.Recvfrom(srv, buf, 0) if err != nil { return rr } rr.elapsed = float64(time.Since(start).Nanoseconds()) / 1e6 t, c := parseICMP(buf) if t == 3 && c == 3 { // Destination port unreachable, type==3 && code==3 rr.done = true } else if t != 11 { // Time Exceeded, type==11 && code in (0,1) return rr } rr.ok = true rr.ip = toStr(from) addrs, err := net.LookupAddr(rr.ip) if err != nil { rr.addr = rr.ip } else { rr.addr = addrs[0] } return rr }
func proxyGo(host *config.Host) error { if host.Host == "" { host.Host = host.Name } if len(host.ResolveNameservers) > 0 { logrus.Debugf("Resolving host: '%s' using nameservers %s", host.Host, host.ResolveNameservers) // FIXME: resolve using custom dns server results, err := net.LookupAddr(host.Host) if err != nil { return err } if len(results) > 0 { host.Host = results[0] } logrus.Debugf("Resolved host is: %s", host.Host) } if host.ResolveCommand != "" { command := commandApplyHost(host.ResolveCommand, host) logrus.Debugf("Resolving host: '%s' using command: '%s'", host.Host, command) args, err := shlex.Split(command) if err != nil { return err } out, err := exec.Command(args[0], args[1:]...).Output() if err != nil { return err } host.Host = strings.TrimSpace(fmt.Sprintf("%s", out)) logrus.Debugf("Resolved host is: %s", host.Host) } logrus.Debugf("Connecting to %s:%d", host.Host, host.Port) conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host.Host, host.Port)) if err != nil { return err } defer conn.Close() logrus.Debugf("Connected to %s:%d", host.Host, host.Port) // Create Stdio pipes c1 := readAndWrite(conn, os.Stdout) c2 := readAndWrite(os.Stdin, conn) select { case err = <-c1: case err = <-c2: } if err != nil { return err } return nil }
func main() { //names, err := net.LookupAddr("2.87.180.214") names, err := net.LookupAddr("147.27.199.212") if err != nil { log.Fatalln(err) } fmt.Println(names) }
func runTraceroute(targetHost string, ipChan chan []string, waitChan chan int) { app := "traceroute" arg0 := "-f" //-f 2 arg1 := "1" //first ttl arg2 := "-m" arg3 := "25" //max ttl arg4 := "-q" arg5 := "3" //number of tries per hop arg6 := "-w" arg7 := "2" //wait time (in seconds) arg8 := "-n" //no dns resolution arg9 := "64" //packet size, bytes cmd := exec.Command(app, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, targetHost, arg9) //execute the commands above, with the host passed out, err := cmd.Output() //output the results of the command if err != nil { fmt.Printf(err.Error()) return } //fmt.Printf("%s\n", string(out)) traceResult := findIPaddr(string(out)) //fmt.Printf("%q\n", traceResult) var ipArray = make([]string, 0) dnsPtr := "" asnResult := "" for i := 2; i < len(traceResult); i++ { currIpAddr := traceResult[i][0] reverseDNSaddr, _ := net.LookupAddr(currIpAddr) if len(reverseDNSaddr) > 0 { //fmt.Printf("%s\n", reverseDNSaddr[0]) dnsPtr = reverseDNSaddr[0] //if it has a PTR, put it in the PTR array section } else { dnsPtr = "noPTR" //everything that does not have a PTR listed } reverseIPaddrResult := reverseIPaddr(currIpAddr) //call the function to reverse the IP address dnsQueryAddress := reverseIPaddrResult + ".origin.asn.cymru.com" //query team cymru database for IP to ASN ipToAsnLookup, _ := net.LookupTXT(dnsQueryAddress) //get TXT record result if len(ipToAsnLookup) > 0 { asnIndex := strings.Index(ipToAsnLookup[0], " ") //if so, parse out the ASN from the result queryString := ipToAsnLookup[0] asnResult = queryString[0:asnIndex] } else { asnResult = "noASN" } ipRowString := currIpAddr + "," + dnsPtr + "," + asnResult ipArray = append(ipArray, ipRowString) } //fmt.Printf("%d\n", len(traceIpArray)) //fmt.Printf("%q\n", ipArray) ipChan <- ipArray waitChan <- 1 return }
func LookupHostname(addr Name) Name { names, err := net.LookupAddr(addr.String()) if err != nil { return Name(addr) } hostname := strings.TrimSuffix(names[0], ".") return Name(hostname) }
func logRequest(req *http.Request) { host, _, _ := net.SplitHostPort(req.RemoteAddr) names, _ := net.LookupAddr(host) if len(names) > 0 { logger.Printf("%s %s from %s (%s)", req.Method, req.URL, req.RemoteAddr, names[0]) } else { logger.Printf("%s %s from %s", req.Method, req.URL, req.RemoteAddr) } }
func getHostname(ip string) string { hostname, err := net.LookupAddr(ip) if err != nil { log.Print("error resolving hostname for ip ", ip, ": ", err) return "" } host := strings.Split(hostname[0], ".") return (host[0]) }
// Traceroute executes traceroute to given destination, using options from TracerouteOptions // and sending updates to chan c // // Outbound packets are UDP packets and inbound packets are ICMP. // // Returns an error or nil if no error occurred func Traceroute(dest *net.IPAddr, options *TracerouteOptions, c chan TraceUpdate) (err error) { var destAddr [4]byte copy(destAddr[:], dest.IP.To4()) socketAddr, err := getSocketAddr() if err != nil { return } timeoutMs := (int64)(options.TimeoutMs) tv := syscall.NsecToTimeval(1000 * 1000 * timeoutMs) ttl := 1 for { // Set up receiving socket recvSocket, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP) if err != nil { log.Fatal("Cannot setup receive socket, please run as root or with CAP_NET_RAW permissions") return err } // Set up sending socket sendSocket, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP) if err != nil { log.Fatal("Cannot setup sending socket") return err } start := time.Now() syscall.SetsockoptInt(sendSocket, 0x0, syscall.IP_TTL, ttl) syscall.SetsockoptTimeval(recvSocket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv) syscall.Bind(recvSocket, &syscall.SockaddrInet4{Port: options.Port, Addr: socketAddr}) syscall.Sendto(sendSocket, []byte{0x0}, 0, &syscall.SockaddrInet4{Port: options.Port, Addr: destAddr}) var p = make([]byte, options.PacketSize) n, from, err := syscall.Recvfrom(recvSocket, p, 0) elapsed := time.Since(start) if err == nil { currAddr := from.(*syscall.SockaddrInet4).Addr hop := TraceUpdate{Success: true, Address: currAddr, N: n, ElapsedTime: elapsed, TTL: ttl} currHost, err := net.LookupAddr(hop.addressString()) if err == nil { hop.Host = currHost[0] } // Send update c <- hop ttl += 1 // We reached the destination if ttl > options.MaxTTL || currAddr == destAddr { ttl = 1 } } else { c <- TraceUpdate{Success: false, TTL: ttl} ttl += 1 } syscall.Close(recvSocket) syscall.Close(sendSocket) } }