dongyishe6689 2019-07-30 19:28
浏览 752


I am running a GRPC server (Server A) listening on a specific port. I want to be able to send a communication to another server (Server B), and have Server B record the incoming address of Server A's connection so that it may later contact Server A.

On Server A, I listen on a port and create a context like such:

lis, err := net.Listen("tcp", "")
ctx, cancel := context.WithTimeout(context.Background(),

Then create a connection like so:

connection, err = grpc.DialContext(ctx, server2Address,
grpc.WithInsecure(), grpc.WithBlock())

Before finally sending a message to an endpoint on Server B, which attempts to read the IP address of Server A's incoming connection

info, _ := peer.FromContext(ctx)
fmt.Printf(info.Addr.String()) // Returns a random port, NOT 6000,

However, the resulting port printed by Server B is random, like 62056 as opposed to 6000 as intended. My assumption is that, on Server A, GRPC dials from a random port - is it possible to force GRPC to dial from port 6000 as opposed to a random port?

  • 写回答

1条回答 默认 最新

  • dousa1630 2019-07-30 23:59

    You can specify the source port like this:

    cc, err := grpc.Dial("", grpc.WithInsecure(),
        grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
            dst, err := net.ResolveTCPAddr("tcp", addr)
            if err != nil {
                return nil, err
            src := &net.TCPAddr{
                IP:   net.ParseIP(""),
                Port: 6000,
            return net.DialTCP("tcp", src, dst)

    However if your server is listening on the same port this will result in an error:

    panic: dial tcp> bind: address already in use

    A different approach would be to pass the address as metadata. On the client you do:

    ctx := context.Background()
    ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("address", ""))
    res, err := grpc_health_v1.NewHealthClient(cc).Check(ctx, &grpc_health_v1.HealthCheckRequest{
        Service: "test",

    And on the server:

    func (s *server) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
        if md, ok := metadata.FromIncomingContext(ctx); ok {
            addr := md.Get("address")
            // addr == ""
        return &grpc_health_v1.HealthCheckResponse{
            Status: grpc_health_v1.HealthCheckResponse_SERVING,
        }, nil

    And a third approach would be to use streaming.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 一道python的homework题,老是非零返回求解
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥20 #数电实验的一些问题
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程
    • ¥15 调制识别中输入为时频图,星座图,眼图等
    • ¥15 数据结构C++的循环、随机数问题