Hello!
The following code does work (the most minimalistic version chosen for clarity) as I connect using port 2100, not a random one:
Code:
#include <arpa/inet.h>
int main(void) {
int sock;
struct sockaddr_in myaddr, remaddr;
socklen_t addrlen;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
remaddr.sin_family = AF_INET;
remaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
remaddr.sin_port = htons(20000);
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
myaddr.sin_port = htons(21000);
bind(sock, (struct sockaddr *) &myaddr, sizeof(struct sockaddr_in));
addrlen = sizeof(myaddr);
connect(sock, (struct sockaddr *) &remaddr, sizeof(remaddr));
return 0;
}
BUT it doesn't use getaddrinfo() which I assume is the preferred way nowadays. The following code:
Code:
#include <unistd.h>
#include <string.h>
#include <netdb.h>
int main(void) {
int sfd, addr;
struct addrinfo hints, *servinfo, *sp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addr = getaddrinfo("127.0.0.1", "20000", &hints, &servinfo);
for(sp = servinfo; sp != NULL; sp = sp->ai_next) {
if ((sfd = socket(sp->ai_family, sp->ai_socktype, sp->ai_protocol)) == -1) {
continue;
}
if ((connect(sfd, sp->ai_addr, sp->ai_addrlen) == -1)) {
continue;
}
break;
}
freeaddrinfo(servinfo);
return 0;
}
works but it doesn't bind() first to force the code to use the source port of my choosing and not the random one.
Question: Where does bind() fit in in the above implementation? Can it be done at all with getaddrinfo()?
Cheers.