问题
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