binding a client to a local port

旧巷老猫 提交于 2019-12-25 04:17:27

问题


I am trying to configure my TCP client to use a specific local port to connect to another TCP server.

I am using the code below but it doesnt' work. Do you know what I am doing wrong and if this is possible? I am using LINUX machine.

Thanks

AFG

    int localport=32000;
    m_clientfd = socket( AF_INET, SOCK_STREAM, 0 );
    assert( m_clientfd >= 0 );

    // someone set the localport        
    struct sockaddr_in sa_loc;
    struct hostent* pLocalHostInfo = gethostbyname( "localhost" );
    long LocalHostAddress;
    memcpy( &LocalHostAddress, pLocalHostInfo->h_addr
    , pLocalHostInfo->h_length );

    // Local
    memset(&sa_loc, 0, sizeof(struct sockaddr_in));
    sa_loc.sin_family = AF_INET;
    sa_loc.sin_port = htons(localport);
    sa_loc.sin_addr.s_addr = LocalHostAddress;
    int ret_bind = bind(m_clientfd, (struct sockaddr *)&sa_loc
    , sizeof(struct sockaddr));
    assert( ret_bind != -1 );

回答1:


int ret_bind = bind(m_clientfd, (struct sockaddr *)&sa_loc,
    sizeof(struct sockaddr));

The last argument should be sizeof(sa_loc) or sizeof(struct sockaddr_in).




回答2:


It looks that using the code below make the app working. It was enough to remove the setup of the local IP.

// Local
memset(&sa_loc, 0, sizeof(struct sockaddr_in));
sa_loc.sin_family = AF_INET;
sa_loc.sin_port = htons(localport);
// sa_loc.sin_addr.s_addr = LocalHostAddress; // COMMENT THIS TO WORK
int ret_bind = bind(m_clientfd, (struct sockaddr *)&sa_loc
, sizeof(struct sockaddr));
assert( ret_bind != -1 );


来源:https://stackoverflow.com/questions/11667763/binding-a-client-to-a-local-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!