0

I am getting error: dial tcp 127.0.0.1:3333: can't assign requested address whenever i try to hit http request concurrently using go routines for 40000 iterations,

it was working fine till 20-30000 iterations, Here is the code I am trying to run:

func TestHttp(c *gin.Context) {
    limit, _ := strconv.Atoi(c.Param("limit"))
    for i := 1; i <= limit; i++ {
        url := "http://hostname/merchant" + strconv.Itoa(i) + "/print-test?p=" + strconv.Itoa(i)
        go MakeRequest2(url, i)
    }
}

/*

 * Function to hit url with get method and close the response body
 */
func MakeRequest2(url string, i int) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    req.Close = true
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
}


func PrintTest(c *gin.Context) {
    a := make(map[string]int)
    for i := 1; i <= 10; i++ {
        a[strconv.Itoa(i)] = i
    }
    fmt.Println(a)
}


I am getting this output:

Get "http://hostname/merchant34096/print-test?p=34096": dial tcp hostname: connect: cannot assign requested address > 

I am expecting to run this code for 1 million iterations concurrently.

Big_Boulard
  • 799
  • 1
  • 13
  • 28
sahil garg
  • 89
  • 5
  • 2
    You keep calling the function without establishing that the resources are freed. Closing sockets [is an asynchronous operation](https://blog.cloudflare.com/how-to-stop-running-out-of-ephemeral-ports-and-start-to-love-long-lived-connections/). Of course you are running out of them. And you can't run this code *concurrently* for 1 million connections, there are not enough TCP ports for that. See also: https://stackoverflow.com/q/39813587. – Lodinn Dec 27 '22 at 10:03

0 Answers0